Class: Fog::AWS::Compute::Mock

Inherits:
Object
  • Object
show all
Defined in:
lib/fog/compute/aws.rb,
lib/fog/compute/requests/aws/create_tags.rb,
lib/fog/compute/requests/aws/delete_tags.rb,
lib/fog/compute/requests/aws/create_image.rb,
lib/fog/compute/requests/aws/attach_volume.rb,
lib/fog/compute/requests/aws/create_volume.rb,
lib/fog/compute/requests/aws/delete_volume.rb,
lib/fog/compute/requests/aws/describe_tags.rb,
lib/fog/compute/requests/aws/detach_volume.rb,
lib/fog/compute/requests/aws/run_instances.rb,
lib/fog/compute/requests/aws/register_image.rb,
lib/fog/compute/requests/aws/stop_instances.rb,
lib/fog/compute/requests/aws/create_key_pair.rb,
lib/fog/compute/requests/aws/create_snapshot.rb,
lib/fog/compute/requests/aws/delete_key_pair.rb,
lib/fog/compute/requests/aws/delete_snapshot.rb,
lib/fog/compute/requests/aws/describe_images.rb,
lib/fog/compute/requests/aws/import_key_pair.rb,
lib/fog/compute/requests/aws/release_address.rb,
lib/fog/compute/requests/aws/start_instances.rb,
lib/fog/compute/requests/aws/allocate_address.rb,
lib/fog/compute/requests/aws/deregister_image.rb,
lib/fog/compute/requests/aws/describe_regions.rb,
lib/fog/compute/requests/aws/describe_volumes.rb,
lib/fog/compute/requests/aws/reboot_instances.rb,
lib/fog/compute/requests/aws/associate_address.rb,
lib/fog/compute/requests/aws/describe_addresses.rb,
lib/fog/compute/requests/aws/describe_instances.rb,
lib/fog/compute/requests/aws/describe_key_pairs.rb,
lib/fog/compute/requests/aws/describe_snapshots.rb,
lib/fog/compute/requests/aws/get_console_output.rb,
lib/fog/compute/requests/aws/terminate_instances.rb,
lib/fog/compute/requests/aws/disassociate_address.rb,
lib/fog/compute/requests/aws/create_security_group.rb,
lib/fog/compute/requests/aws/delete_security_group.rb,
lib/fog/compute/requests/aws/modify_image_attributes.rb,
lib/fog/compute/requests/aws/describe_security_groups.rb,
lib/fog/compute/requests/aws/modify_snapshot_attribute.rb,
lib/fog/compute/requests/aws/describe_availability_zones.rb,
lib/fog/compute/requests/aws/describe_reserved_instances.rb,
lib/fog/compute/requests/aws/revoke_security_group_ingress.rb,
lib/fog/compute/requests/aws/authorize_security_group_ingress.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Mock

Returns a new instance of Mock.



148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/fog/compute/aws.rb', line 148

def initialize(options={})
  unless options.delete(:provider)
    location = caller.first
    warning = "[yellow][WARN] Fog::AWS::Compute.new is deprecated, use Fog::Compute.new(:provider => 'AWS') instead[/]"
    warning << " [light_black](" << location << ")[/] "
    Formatador.display_line(warning)
  end

  @aws_access_key_id = options[:aws_access_key_id]
  @region = options[:region] || 'us-east-1'
  @data = self.class.data[@region][@aws_access_key_id]
  @owner_id = @data[:owner_id]
end

Class Method Details

.dataObject



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
# File 'lib/fog/compute/aws.rb', line 92

def self.data
  @data ||= Hash.new do |hash, region|
    owner_id = Fog::AWS::Mock.owner_id
    hash[region] = Hash.new do |region_hash, key|
      region_hash[key] = {
        :deleted_at => {},
        :addresses  => {},
        :images     => {},
        :instances  => {},
        :key_pairs  => {},
        :limits     => { :addresses => 5 },
        :owner_id   => owner_id,
        :security_groups => {
          'default' => {
            'groupDescription'  => 'default group',
            'groupName'         => 'default',
            'ipPermissions'     => [
              {
                'groups'      => [{'groupName' => 'default', 'userId' => owner_id}],
                'fromPort'    => -1,
                'toPort'      => -1,
                'ipProtocol'  => 'icmp',
                'ipRanges'    => []
              },
              {
                'groups'      => [{'groupName' => 'default', 'userId' => owner_id}],
                'fromPort'    => 0,
                'toPort'      => 65535,
                'ipProtocol'  => 'tcp',
                'ipRanges'    => []
              },
              {
                'groups'      => [{'groupName' => 'default', 'userId' => owner_id}],
                'fromPort'    => 0,
                'toPort'      => 65535,
                'ipProtocol'  => 'udp',
                'ipRanges'    => []
              }
            ],
            'ownerId'           => owner_id
          }
        },
        :snapshots => {},
        :volumes => {},
        :tags => {}
      }
    end
  end
end

.reset_data(keys = data.keys) ⇒ Object



142
143
144
145
146
# File 'lib/fog/compute/aws.rb', line 142

def self.reset_data(keys=data.keys)
  for key in [*keys]
    data.delete(key)
  end
end

Instance Method Details

#allocate_addressObject



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/fog/compute/requests/aws/allocate_address.rb', line 26

def allocate_address
  response = Excon::Response.new
  if describe_addresses.body['addressesSet'].size < @data[:limits][:addresses]
    response.status = 200
    public_ip = Fog::AWS::Mock.ip_address
    data ={
      'instanceId' => nil,
      'publicIp'   => public_ip
    }
    @data[:addresses][public_ip] = data
    response.body = {
      'publicIp'  => public_ip,
      'requestId' => Fog::AWS::Mock.request_id
    }
    response
  else
    response.status = 400
    response.body = "<?xml version=\"1.0\"?><Response><Errors><Error><Code>AddressLimitExceeded</Code><Message>Too many addresses allocated</Message></Error></Errors><RequestID>#{Fog::AWS::Mock.request_id}</RequestID></Response>"
    raise(Excon::Errors.status_error({:expects => 200}, response))
  end
end

#associate_address(instance_id, public_ip) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/fog/compute/requests/aws/associate_address.rb', line 31

def associate_address(instance_id, public_ip)
  response = Excon::Response.new
  response.status = 200
  instance = @data[:instances][instance_id]
  address = @data[:addresses][public_ip]
  if instance && address
    address['instanceId'] = instance_id
    instance['originalIpAddress'] = instance['ipAddress']
    instance['ipAddress'] = public_ip
    instance['dnsName'] = Fog::AWS::Mock.dns_name_for(public_ip)
    response.status = 200
    response.body = {
      'requestId' => Fog::AWS::Mock.request_id,
      'return'    => true
    }
    response
  elsif !instance
    raise Fog::AWS::Compute::NotFound.new("The instance ID '#{instance_id}' does not exist")
  elsif !address
    raise Fog::AWS::Compute::Error.new("AuthFailure => The address '#{public_ip}' does not belong to you.")
  end
end

#attach_volume(instance_id, volume_id, device) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/fog/compute/requests/aws/attach_volume.rb', line 39

def attach_volume(instance_id, volume_id, device)
  response = Excon::Response.new
  if instance_id && volume_id && device
    response.status = 200
    instance = @data[:instances][instance_id]
    volume = @data[:volumes][volume_id]
    if instance && volume
      data = {
        'attachTime'  => Time.now,
        'device'      => device,
        'instanceId'  => instance_id,
        'status'      => 'attaching',
        'volumeId'    => volume_id
      }
      volume['attachmentSet'] = [data]
      volume['status'] = 'attaching'
      response.status = 200
      response.body = {
        'requestId' => Fog::AWS::Mock.request_id
      }.merge!(data)
      response
    elsif !instance
      raise Fog::AWS::Compute::NotFound.new("The instance ID '#{instance_id}' does not exist.")
    elsif !volume
      raise Fog::AWS::Compute::NotFound.new("The volume '#{volume_id}' does not exist.")
    end
  else
    message = 'MissingParameter => '
    if !instance_id
      message << 'The request must contain the parameter instance_id'
    elsif !volume_id
      message << 'The request must contain the parameter volume_id'
    else
      message << 'The request must contain the parameter device'
    end
    raise Fog::AWS::Compute::Error.new(message)
  end
end

#authorize_security_group_ingress(options = {}) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/fog/compute/requests/aws/authorize_security_group_ingress.rb', line 37

def authorize_security_group_ingress(options = {})
  response = Excon::Response.new
  group = @data[:security_groups][options['GroupName']]

  if group
    group['ipPermissions'] ||= []
    if options['GroupName'] && options['SourceSecurityGroupName'] && options['SourceSecurityGroupOwnerId']
      ['tcp', 'udp'].each do |protocol|
        group['ipPermissions'] << {
          'groups'      => [{'groupName' => options['GroupName'], 'userId' => @owner_id}],
          'fromPort'    => 1,
          'ipRanges'    => [],
          'ipProtocol'  => protocol,
          'toPort'      => 65535
        }
      end
      group['ipPermissions'] << {
        'groups'      => [{'groupName' => options['GroupName'], 'userId' => @owner_id}],
        'fromPort'    => -1,
        'ipRanges'    => [],
        'ipProtocol'  => 'icmp',
        'toPort'      => -1
      }
    else
      group['ipPermissions'] << {
        'groups'      => [],
        'fromPort'    => options['FromPort'],
        'ipRanges'    => [],
        'ipProtocol'  => options['IpProtocol'],
        'toPort'      => options['ToPort']
      }
      if options['CidrIp']
        group['ipPermissions'].last['ipRanges'] << { 'cidrIp' => options['CidrIp'] }
      end
    end
    response.status = 200
    response.body = {
      'requestId' => Fog::AWS::Mock.request_id,
      'return'    => true
    }
    response
  else
    raise Fog::AWS::Compute::NotFound.new("The security group '#{options['GroupName']}' does not exist")
  end
end

#create_image(instance_id, name, description, no_reboot = false) ⇒ Object

Usage

AWS.create_image(“i-ac65ee8c”, “test”, “something”)



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/fog/compute/requests/aws/create_image.rb', line 41

def create_image(instance_id, name, description, no_reboot = false)
  response = Excon::Response.new
  if instance_id && !name.empty?
    response.status = 200
    response.body = {
      'requestId' => Fog::AWS::Mock.request_id,
      'imageId' => Fog::AWS::Mock.image_id
    }
  else
    response.status = 400
    response.body = {
      'Code' => 'InvalidParameterValue'
    }
    if name.empty?
      response.body['Message'] = "Invalid value '' for name. Must be specified."
    end
  end
  response
end

#create_key_pair(key_name) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/fog/compute/requests/aws/create_key_pair.rb', line 32

def create_key_pair(key_name)
  response = Excon::Response.new
  unless @data[:key_pairs][key_name]
    response.status = 200
    data = {
      'keyFingerprint'  => Fog::AWS::Mock.key_fingerprint,
      'keyMaterial'     => Fog::AWS::Mock.key_material,
      'keyName'         => key_name
    }
    @data[:key_pairs][key_name] = data
    response.body = {
      'requestId' => Fog::AWS::Mock.request_id
    }.merge!(data)
    response
  else
    raise Fog::AWS::Compute::Error.new("InvalidKeyPair.Duplicate => The keypair '#{key_name}' already exists.")
  end
end

#create_security_group(name, description) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/fog/compute/requests/aws/create_security_group.rb', line 30

def create_security_group(name, description)
  response = Excon::Response.new
  unless @data[:security_groups][name]
    data = {
      'groupDescription'  => CGI.escape(description).gsub('%20', '+'),
      'groupName'         => CGI.escape(name).gsub('%20', '+'),
      'ipPermissions'     => [],
      'ownerId'           => @owner_id
    }
    @data[:security_groups][name] = data
    response.body = {
      'requestId' => Fog::AWS::Mock.request_id,
      'return'    => true
    }
    response
  else
    raise Fog::AWS::Compute::Error.new("InvalidGroup.Duplicate => The security group '#{name}' already exists")
  end
end

#create_snapshot(volume_id, description = nil) ⇒ Object

Usage

AWS.create_snapshot(“vol-f7c23423”, “latest snapshot”)



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/fog/compute/requests/aws/create_snapshot.rb', line 41

def create_snapshot(volume_id, description = nil)
  response = Excon::Response.new
  if volume = @data[:volumes][volume_id]
    response.status = 200
    snapshot_id = Fog::AWS::Mock.snapshot_id
    data = {
      'description' => description,
      'ownerId'     => @owner_id,
      'progress'    => nil,
      'snapshotId'  => snapshot_id,
      'startTime'   => Time.now,
      'status'      => 'pending',
      'volumeId'    => volume_id,
      'volumeSize'  => volume['size']
    }
    @data[:snapshots][snapshot_id] = data
    response.body = {
      'requestId' => Fog::AWS::Mock.request_id
    }.merge!(data)
    @data[:snapshots][snapshot_id]['tagSet'] = {}
  else
    response.status = 400
    raise(Excon::Errors.status_error({:expects => 200}, response))
  end
  response
end

#create_tags(resources, tags) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/fog/compute/requests/aws/create_tags.rb', line 38

def create_tags(resources, tags)
  resources = [*resources]

  tagged = resources.map do |resource_id|
    type = case resource_id
    when /^ami\-[a-z0-9]{8}$/i
      'image'
    when /^i\-[a-z0-9]{8}$/i
      'instance'
    when /^snap\-[a-z0-9]{8}$/i
      'snapshot'
    when /^vol\-[a-z0-9]{8}$/i
      'volume'
    end
    if type && @data[:"#{type}s"][resource_id]
      { 'resourceId' => resource_id, 'resourceType' => type }
    else
      raise(Fog::Service::NotFound.new("The #{type} ID '#{resource_id}' does not exist"))
    end
  end

  tags.each do |key, value|
    @data[:tags][key] ||= {}
    @data[:tags][key][value] ||= []
    @data[:tags][key][value] = @data[:tags][key][value] & tagged
  end

  response = Excon::Response.new
  response.status = 200
  response.body = {
    'requestId' => Fog::AWS::Mock.request_id,
    'return'    => true
  }
  response
end

#create_volume(availability_zone, size, snapshot_id = nil) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/fog/compute/requests/aws/create_volume.rb', line 38

def create_volume(availability_zone, size, snapshot_id = nil)
  response = Excon::Response.new
  if availability_zone && size
    response.status = 200
    volume_id = Fog::AWS::Mock.volume_id
    data = {
      'availabilityZone'  => availability_zone,
      'attachmentSet'     => [],
      'createTime'        => Time.now,
      'size'              => size,
      'snapshotId'        => snapshot_id,
      'status'            => 'creating',
      'tagSet'            => {},
      'volumeId'          => volume_id
    }
    @data[:volumes][volume_id] = data
    response.body = {
      'requestId' => Fog::AWS::Mock.request_id
    }.merge!(data.reject {|key,value| !['availabilityZone','createTime','size','snapshotId','status','volumeId'].include?(key) })
  else
    response.status = 400
    response.body = {
      'Code' => 'MissingParameter'
    }
    unless availability_zone
      response.body['Message'] = 'The request must contain the parameter availability_zone'
    else
      response.body['Message'] = 'The request must contain the parameter size'
    end
  end
  response
end

#delete_key_pair(key_name) ⇒ Object



29
30
31
32
33
34
35
36
37
38
# File 'lib/fog/compute/requests/aws/delete_key_pair.rb', line 29

def delete_key_pair(key_name)
  response = Excon::Response.new
  @data[:key_pairs].delete(key_name)
  response.status = 200
  response.body = {
    'requestId' => Fog::AWS::Mock.request_id,
    'return'    => true
  }
  response
end

#delete_security_group(name) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/fog/compute/requests/aws/delete_security_group.rb', line 28

def delete_security_group(name)
  response = Excon::Response.new
  if @data[:security_groups][name]
    @data[:security_groups].delete(name)
    response.status = 200
    response.body = {
      'requestId' => Fog::AWS::Mock.request_id,
      'return'    => true
    }
    response
  else
    raise Fog::AWS::Compute::NotFound.new("The security group '#{name}' does not exist")
  end
end

#delete_snapshot(snapshot_id) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/fog/compute/requests/aws/delete_snapshot.rb', line 29

def delete_snapshot(snapshot_id)
  response = Excon::Response.new
  if snapshot = @data[:snapshots].delete(snapshot_id)
    response.status = true
    response.body = {
      'requestId' => Fog::AWS::Mock.request_id,
      'return'    => true
    }
    response
  else
    raise Fog::AWS::Compute::NotFound.new("The snapshot '#{snapshot_id}' does not exist.")
  end
end

#delete_tags(resources, tags) ⇒ Object



38
39
40
# File 'lib/fog/compute/requests/aws/delete_tags.rb', line 38

def delete_tags(resources, tags)
  Fog::Mock.not_implemented
end

#delete_volume(volume_id) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/fog/compute/requests/aws/delete_volume.rb', line 29

def delete_volume(volume_id)
  response = Excon::Response.new
  if volume = @data[:volumes][volume_id]
    if volume["attachmentSet"].any?
      attach = volume["attachmentSet"].first
      raise Fog::AWS::Compute::Error.new("Client.VolumeInUse => Volume #{volume_id} is currently attached to #{attach["instanceId"]}")
    end
    @data[:deleted_at][volume_id] = Time.now
    volume['status'] = 'deleting'
    response.status = 200
    response.body = {
      'requestId' => Fog::AWS::Mock.request_id,
      'return'    => true
    }
    response
  else
    raise Fog::AWS::Compute::NotFound.new("The volume '#{volume_id}' does not exist.")
  end
end

#deregister_image(image_id) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/fog/compute/requests/aws/deregister_image.rb', line 30

def deregister_image(image_id)
  response = Excon::Response.new
  if image_id 
    response.status = 200
    response.body = {
      'requestId' => Fog::AWS::Mock.request_id,
      'return' => "true"
    }
    response
  else
    message = 'MissingParameter => '
    if !instance_id
      message << 'The request must contain the parameter image_id'
    end
    raise Fog::AWS::Compute::Error.new(message)
  end
end

#describe_addresses(filters = {}) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/fog/compute/requests/aws/describe_addresses.rb', line 37

def describe_addresses(filters = {})
  unless filters.is_a?(Hash)
    Formatador.display_line("[yellow][WARN] describe_addresses with #{filters.class} param is deprecated, use describe_addresses('public-ip' => []) instead[/] [light_black](#{caller.first})[/]")
    filters = {'public-ip' => [*filters]}
  end

  response = Excon::Response.new

  addresses_set = @data[:addresses].values

  aliases = {'public-ip' => 'publicIp', 'instance-id' => 'instanceId'}
  for filter_key, filter_value in filters
    aliased_key = aliases[filter_key]
    addresses_set = addresses_set.reject{|address| ![*filter_value].include?(address[aliased_key])}
  end

  response.status = 200
  response.body = {
    'requestId'     => Fog::AWS::Mock.request_id,
    'addressesSet'  => addresses_set
  }
  response
end

#describe_availability_zones(filters = {}) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/fog/compute/requests/aws/describe_availability_zones.rb', line 38

def describe_availability_zones(filters = {})
  unless filters.is_a?(Hash)
    Formatador.display_line("[yellow][WARN] describe_availability_zones with #{filters.class} param is deprecated, use describe_availability_zones('zone-name' => []) instead[/] [light_black](#{caller.first})[/]")
    filters = {'public-ip' => [*filters]}
  end

  response = Excon::Response.new

  availability_zone_info = [
    {"messageSet" => [], "regionName" => "us-east-1", "zoneName" => "us-east-1a", "zoneState" => "available"},
    {"messageSet" => [], "regionName" => "us-east-1", "zoneName" => "us-east-1b", "zoneState" => "available"},
    {"messageSet" => [], "regionName" => "us-east-1", "zoneName" => "us-east-1c", "zoneState" => "available"},
    {"messageSet" => [], "regionName" => "us-east-1", "zoneName" => "us-east-1d", "zoneState" => "available"},
  ]

  aliases = {'region-name' => 'regionName', 'zone-name' => 'zoneName', 'state' => 'zoneState'}
  for filter_key, filter_value in filters
    aliased_key = aliases[filter_key]
    availability_zone_info = availability_zone_info.reject{|availability_zone| ![*filter_value].include?(availability_zone[aliased_key])}
  end

  response.status = 200
  response.body = {
    'availabilityZoneInfo'  => availability_zone_info,
    'requestId'             => Fog::AWS::Mock.request_id
  }
  response
end

#describe_images(filters = {}) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
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
# File 'lib/fog/compute/requests/aws/describe_images.rb', line 58

def describe_images(filters = {})
  unless filters.is_a?(Hash)
    Formatador.display_line("[yellow][WARN] describe_images with #{filters.class} param is deprecated, use describe_snapshots('snapshot-id' => []) instead[/] [light_black](#{caller.first})[/]")
    filters = {'snapshot-id' => [*filters]}
  end
  
  if filters.keys.any? {|key| key =~ /^block-device/}
    Formatador.display_line("[yellow][WARN] describe_images block-device-mapping filters are not yet mocked[/] [light_black](#{caller.first})[/]")
    Fog::Mock.not_implemented
  end
  
  if filters.keys.any? {|key| key =~ /^tag/}
    Formatador.display_line("[yellow][WARN] describe_images tag filters are not yet mocked[/] [light_black](#{caller.first})[/]")
    Fog::Mock.not_implemented
  end
  
  response = Excon::Response.new
  
  aliases = {
    'architecture'        => 'architecture',
    'description'         => 'description',
    'hypervisor'          => 'hypervisor',
    'image-id'            => 'imageId',
    'image-type'          => 'imageType',
    'is-public'           => 'isPublic',
    'kernel-id'           => 'kernelId',
    'manifest-location'   => 'manifestLocation',
    'name'                => 'name',            
    'owner-id'            => 'imageOwnerId',
    'ramdisk-id'          => 'ramdiskId',
    'root-device-name'    => 'rootDeviceName',
    'root-device-type'    => 'rootDeviceType',
    'state'               => 'imageState',
    'virtualization-type' => 'virtualizationType'
  }
  
  image_set = @data[:images].values
  
  for filter_key, filter_value in filters
    aliased_key = aliases[filter_key]
    image_set = image_set.reject{|image| ![*filter_value].include?(image[aliased_key])}
  end

  response.status = 200
  response.body = {
    'requestId' => Fog::AWS::Mock.request_id,
    'imagesSet' => image_set
  }
  response
end

#describe_instances(filters = {}) ⇒ Object



71
72
73
74
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
# File 'lib/fog/compute/requests/aws/describe_instances.rb', line 71

def describe_instances(filters = {})
  unless filters.is_a?(Hash)
    Formatador.display_line("[yellow][WARN] describe_instances with #{filters.class} param is deprecated, use describe_instances('instance-id' => []) instead[/] [light_black](#{caller.first})[/]")
    filters = {'instance-id' => [*filters]}
  end

  if filters.keys.any? {|key| key =~ /^tag/}
    Formatador.display_line("[yellow][WARN] describe_instances tag filters are not yet mocked[/] [light_black](#{caller.first})[/]")
    Fog::Mock.not_implemented
  end

  response = Excon::Response.new

  instance_set = @data[:instances].values

  aliases = {
    'architecture'      => 'architecture',
    'availability-zone' => 'availabilityZone',
    'client-token'      => 'clientToken',
    'dns-token'         => 'dnsName',
    'group-id'          => 'groupId',
    'image-id'          => 'imageId',
    'instance-id'       => 'instanceId',
    'instance-lifecycle'  => 'instanceLifecycle',
    'instance-type'     => 'instanceType',
    'ip-address'        => 'ipAddress',
    'kernel-id'         => 'kernelId',
    'key-name'          => 'key-name',
    'launch-index'      => 'launchIndex',
    'launch-time'       => 'launchTime',
    'monitoring-state'  => 'monitoringState',
    'owner-id'          => 'ownerId',
    'placement-group-name' => 'placementGroupName',
    'platform'          => 'platform',
    'private-dns-name'  => 'privateDnsName',
    'private-ip-address'  => 'privateIpAddress',
    'product-code'      => 'productCode',
    'ramdisk-id'        => 'ramdiskId',
    'reason'            => 'reason',
    'requester-id'      => 'requesterId',
    'reservation-id'    => 'reservationId',
    'root-device-name'  => 'rootDeviceName',
    'root-device-type'  => 'rootDeviceType',
    'spot-instance-request-id' => 'spotInstanceRequestId',
    'subnet-id'         => 'subnetId',
    'virtualization-type' => 'virtualizationType',
    'vpc-id'            => 'vpcId'
  }
  block_device_mapping_aliases = {
    'attach-time'           => 'attachTime',
    'delete-on-termination' => 'deleteOnTermination',
    'device-name'           => 'deviceName',
    'status'                => 'status',
    'volume-id'             => 'volumeId',
  }
  instance_state_aliases = {
    'code' => 'code',
    'name' => 'name'
  }
  state_reason_aliases = {
    'code'    => 'code',
    'message' => 'message'
  }
  for filter_key, filter_value in filters
    if block_device_mapping_key = filter_key.split('block-device-mapping.')[1]
      aliased_key = block_device_mapping_aliases[block_device_mapping_key]
      instance_set = instance_set.reject{|instance| !instance['blockDeviceMapping'].detect {|block_device_mapping| [*filter_value].include?(block_device_mapping[aliased_key])}}
    elsif instance_state_key = filter_key.split('instance-state-')[1]
      aliased_key = instance_state_aliases[instance_state_key]
      instance_set = instance_set.reject{|instance| ![*filter_value].include?(instance['instanceState'][aliased_key])}
    elsif state_reason_key = filter_key.split('state-reason-')[1]
      aliased_key = state_reason_aliases[state_reason_key]
      instance_set = instance_set.reject{|instance| ![*filter_value].include?(instance['stateReason'][aliased_key])}
    else
      aliased_key = aliases[filter_key]
      instance_set = instance_set.reject {|instance| ![*filter_value].include?(instance[aliased_key])}
    end
  end

  response.status = 200
  reservation_set = {}

  instance_set.each do |instance|
    case instance['instanceState']['name']
    when 'pending'
      if Time.now - instance['launchTime'] > Fog::Mock.delay
        instance['ipAddress']         = Fog::AWS::Mock.ip_address
        instance['dnsName']           = Fog::AWS::Mock.dns_name_for(instance['ipAddress'])
        instance['privateIpAddress']  = Fog::AWS::Mock.ip_address
        instance['privateDnsName']    = Fog::AWS::Mock.private_dns_name_for(instance['privateIpAddress'])
        instance['instanceState']     = { 'code' => 16, 'name' => 'running' }
      end
    when 'rebooting'
      instance['instanceState'] = { 'code' => 16, 'name' => 'running' }
    when 'shutting-down'
      if Time.now - @data[:deleted_at][instance['instanceId']] > Fog::Mock.delay * 2
        @data[:deleted_at].delete(instance['instanceId'])
        @data[:instances].delete(instance['instanceId'])
      elsif Time.now - @data[:deleted_at][instance['instanceId']] > Fog::Mock.delay
        instance['instanceState'] = { 'code' => 48, 'name' => 'terminating' }
      end
    when 'terminating'
      if Time.now - @data[:deleted_at][instance['instanceId']] > Fog::Mock.delay
        @data[:deleted_at].delete(instance['instanceId'])
        @data[:instances].delete(instance['instanceId'])
      end
    end

    if @data[:instances][instance['instanceId']]

      reservation_set[instance['reservationId']] ||= {
        'groupSet'      => instance['groupSet'],
        'instancesSet'  => [],
        'ownerId'       => instance['ownerId'],
        'reservationId' => instance['reservationId']
      }
      reservation_set[instance['reservationId']]['instancesSet'] << instance.reject{|key,value| !['amiLaunchIndex', 'architecture', 'blockDeviceMapping', 'clientToken', 'dnsName', 'imageId', 'instanceId', 'instanceState', 'instanceType', 'ipAddress', 'kernelId', 'keyName', 'launchTime', 'monitoring', 'placement', 'privateDnsName', 'privateIpAddress', 'productCodes', 'ramdiskId', 'reason', 'rootDeviceType', 'stateReason', 'tagSet'].include?(key)}
    end
  end

  response.body = {
    'requestId'       => Fog::AWS::Mock.request_id,
    'reservationSet' => reservation_set.values
  }
  response
end

#describe_key_pairs(filters = {}) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/fog/compute/requests/aws/describe_key_pairs.rb', line 37

def describe_key_pairs(filters = {})
  unless filters.is_a?(Hash)
    Formatador.display_line("[yellow][WARN] describe_key_pairs with #{filters.class} param is deprecated, use describe_key_pairs('key-name' => []) instead[/] [light_black](#{caller.first})[/]")
    filters = {'key-name' => [*filters]}
  end

  response = Excon::Response.new

  key_set = @data[:key_pairs].values

  aliases = {'fingerprint' => 'keyFingerprint', 'key-name' => 'keyName'}
  for filter_key, filter_value in filters
    aliased_key = aliases[filter_key]
    key_set = key_set.reject{|key_pair| ![*filter_value].include?(key_pair[aliased_key])}
  end

  response.status = 200
  response.body = {
    'requestId' => Fog::AWS::Mock.request_id,
    'keySet'    => key_set.map do |key_pair|
      key_pair.reject {|key,value| !['keyFingerprint', 'keyName'].include?(key)}
    end
  }
  response
end

#describe_regions(filters = {}) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/fog/compute/requests/aws/describe_regions.rb', line 37

def describe_regions(filters = {})
  unless filters.is_a?(Hash)
    Formatador.display_line("[yellow][WARN] describe_regions with #{filters.class} param is deprecated, use describe_regions('region-name' => []) instead[/] [light_black](#{caller.first})[/]")
    filters = {'region-name' => [*filters]}
  end

  response = Excon::Response.new
  region_info = [
    {"regionName"=>"eu-west-1", "regionEndpoint"=>"eu-west-1.ec2.amazonaws.com"},
    {"regionName"=>"us-east-1", "regionEndpoint"=>"us-east-1.ec2.amazonaws.com"}
  ]

  aliases = {'region-name' => 'regionName', 'endpoint' => 'regionEndpoint'}
  for filter_key, filter_value in filters
    aliased_key = aliases[filter_key]
    region_info = region_info.reject{|region| ![*filter_value].include?(region[aliased_key])}
  end

  response.status = 200
  response.body = {
    'requestId'   => Fog::AWS::Mock.request_id,
    'regionInfo'  => region_info
  }
  response
end

#describe_reserved_instances(filters = {}) ⇒ Object



45
46
47
# File 'lib/fog/compute/requests/aws/describe_reserved_instances.rb', line 45

def describe_reserved_instances(filters = {})
  Fog::Mock.not_implemented
end

#describe_security_groups(filters = {}) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/fog/compute/requests/aws/describe_security_groups.rb', line 47

def describe_security_groups(filters = {})
  unless filters.is_a?(Hash)
    Formatador.display_line("[yellow][WARN] describe_security_groups with #{filters.class} param is deprecated, use describe_security_groups('group-name' => []) instead[/] [light_black](#{caller.first})[/]")
    filters = {'group-name' => [*filters]}
  end

  response = Excon::Response.new

  security_group_info = @data[:security_groups].values

  aliases = {
    'description' => 'groupDescription',
    'group-name'  => 'groupName',
    'owner-id'    => 'ownerId'
  }
  permission_aliases = {
    'cidr'      => 'cidrIp',
    'from-port' => 'fromPort',
    'protocol'  => 'ipProtocol',
    'to-port'   => 'toPort'
  }
  for filter_key, filter_value in filters
    if permission_key = filter_key.split('ip-permission.')[1]
      if permission_key == 'group-name'
        security_group_info = security_group_info.reject{|security_group| !security_group['ipPermissions']['groups'].detect {|group| [*filter_value].include?(group['groupName'])}}
      elsif permission_key == 'user-id'
        security_group_info = security_group_info.reject{|security_group| !security_group['ipPermissions']['groups'].detect {|group| [*filter_value].include?(group['userId'])}}
      else
        aliased_key = permission_aliases[filter_key]
        security_group_info = security_group_info.reject{|security_group| !security_group['ipPermissions'].detect {|permission| [*filter_value].include?(permission[aliased_key])}}
      end
    else
      aliased_key = aliases[filter_key]
      security_group_info = security_group_info.reject{|security_group| ![*filter_value].include?(security_group[aliased_key])}
    end
  end

  response.status = 200
  response.body = {
    'requestId'         => Fog::AWS::Mock.request_id,
    'securityGroupInfo' => security_group_info
  }
  response
end

#describe_snapshots(filters = {}, options = {}) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
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
# File 'lib/fog/compute/requests/aws/describe_snapshots.rb', line 53

def describe_snapshots(filters = {}, options = {})
  unless filters.is_a?(Hash)
    Formatador.display_line("[yellow][WARN] describe_snapshots with #{filters.class} param is deprecated, use describe_snapshots('snapshot-id' => []) instead[/] [light_black](#{caller.first})[/]")
    filters = {'snapshot-id' => [*filters]}
  end
  unless options.empty?
    Formatador.display_line("[yellow][WARN] describe_snapshots with a second param is deprecated, use describe_snapshots(options) instead[/] [light_black](#{caller.first})[/]")
  end

  if filters.keys.any? {|key| key =~ /^tag/}
    Formatador.display_line("[yellow][WARN] describe_snapshots tag filters are not yet mocked[/] [light_black](#{caller.first})[/]")
    Fog::Mock.not_implemented
  end

  response = Excon::Response.new

  snapshot_set = @data[:snapshots].values

  if filters.delete('owner-alias')
    Formatador.display_line("[yellow][WARN] describe_snapshots with owner-alias is not mocked[/] [light_black](#{caller.first})[/]")
  end
  if filters.delete('RestorableBy')
    Formatador.display_line("[yellow][WARN] describe_snapshots with RestorableBy is not mocked[/] [light_black](#{caller.first})[/]")
  end

  aliases = {
    'description' => 'description',
    'owner-id'    => 'ownerId',
    'progress'    => 'progress',
    'snapshot-id' => 'snapshotId',
    'start-time'  => 'startTime',
    'status'      => 'status',
    'volume-id'   => 'volumeId',
    'volume-size' => 'volumeSize'
  }
  for filter_key, filter_value in filters
    aliased_key = aliases[filter_key]
    snapshot_set = snapshot_set.reject{|snapshot| ![*filter_value].include?(snapshot[aliased_key])}
  end

  snapshot_set.each do |snapshot|
    case snapshot['status']
    when 'in progress', 'pending'
      if Time.now - snapshot['startTime'] > Fog::Mock.delay * 2
        snapshot['progress']  = '100%'
        snapshot['status']    = 'completed'
      elsif Time.now - snapshot['startTime'] > Fog::Mock.delay
        snapshot['progress']  = '50%'
        snapshot['status']    = 'in progress'
      else
        snapshot['progress']  = '0%'
        snapshot['status']    = 'in progress'
      end
    end
  end

  response.status = 200
  response.body = {
    'requestId' => Fog::AWS::Mock.request_id,
    'snapshotSet' => snapshot_set
  }
  response
end

#describe_tags(filters = {}) ⇒ Object



35
36
37
# File 'lib/fog/compute/requests/aws/describe_tags.rb', line 35

def describe_tags(filters = {})
  Fog::Mock.not_implemented
end

#describe_volumes(filters = {}) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
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
# File 'lib/fog/compute/requests/aws/describe_volumes.rb', line 47

def describe_volumes(filters = {})
  unless filters.is_a?(Hash)
    Formatador.display_line("[yellow][WARN] describe_volumes with #{filters.class} param is deprecated, use describe_volumes('volume-id' => []) instead[/] [light_black](#{caller.first})[/]")
    filters = {'volume-id' => [*filters]}
  end

  if filters.keys.any? {|key| key =~ /^tag/}
    Formatador.display_line("[yellow][WARN] describe_volumes tag filters are not yet mocked[/] [light_black](#{caller.first})[/]")
    Fog::Mock.not_implemented
  end

  response = Excon::Response.new

  volume_set = @data[:volumes].values

  aliases = {
    'availability-zone' => 'availabilityZone',
    'create-time' => 'createTime',
    'size' => 'size',
    'snapshot-id' => 'snapshotId',
    'status' => 'status',
    'volume-id' => 'volumeId'
  }
  attachment_aliases = {
    'attach-time' => 'attachTime',
    'delete-on-termination' => 'deleteOnTermination',
    'device'      => 'device',
    'instance-id' => 'instanceId',
    'status'      => 'status'
  }
  for filter_key, filter_value in filters
    if attachment_key = filter_key.split('attachment.')[1]
      aliased_key = permission_aliases[filter_key]
      volume_set = volume_set.reject{|volume| !volume['attachmentSet'].detect {|attachment| [*filter_value].include?(attachment[aliased_key])}}
    else
      aliased_key = aliases[filter_key]
      volume_set = volume_set.reject{|volume| ![*filter_value].include?(volume[aliased_key])}
    end
  end

  volume_set.each do |volume|
    case volume['status']
    when 'attaching'
      if Time.now - volume['attachmentSet'].first['attachTime'] > Fog::Mock.delay
        volume['attachmentSet'].first['status'] = 'in-use'
        volume['status'] = 'in-use'
      end
    when 'creating'
      if Time.now - volume['createTime'] > Fog::Mock.delay
        volume['status'] = 'available'
      end
    when 'deleting'
      if Time.now - @data[:deleted_at][volume['volumeId']] > Fog::Mock.delay
        @data[:deleted_at].delete(volume['volumeId'])
        @data[:volumes].delete(volume['volumeId'])
      end
    end
  end
  volume_set = volume_set.reject {|volume| !@data[:volumes][volume['volumeId']]}

  response.status = 200
  response.body = {
    'requestId' => Fog::AWS::Mock.request_id,
    'volumeSet' => volume_set
  }
  response
end

#detach_volume(volume_id, options = {}) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/fog/compute/requests/aws/detach_volume.rb', line 39

def detach_volume(volume_id, options = {})
  response = Excon::Response.new
  response.status = 200
  if (volume = @data[:volumes][volume_id]) && !volume['attachmentSet'].empty?
    data = volume['attachmentSet'].pop
    volume['status'] = 'available'
    response.status = 200
    response.body = {
      'requestId' => Fog::AWS::Mock.request_id
    }.merge!(data)
    response
  else
    raise Fog::AWS::Compute::NotFound.new("The volume '#{volume_id}' does not exist.")
  end
end

#disassociate_address(public_ip) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/fog/compute/requests/aws/disassociate_address.rb', line 29

def disassociate_address(public_ip)
  response = Excon::Response.new
  response.status = 200
  if address = @data[:addresses][public_ip]
    instance_id = address['instanceId']
    instance = @data[:instances][instance_id]
    instance['ipAddress']         = instance['originalIpAddress']
    instance['dnsName']           = Fog::AWS::Mock.dns_name_for(instance['ipAddress'])
    address['instanceId'] = nil
    response.status = 200
    response.body = {
      'requestId' => Fog::AWS::Mock.request_id,
      'return'    => true
    }
    response
  else
    raise Fog::AWS::Compute::Error.new("AuthFailure => The address '#{public_ip}' does not belong to you.")
  end
end

#get_console_output(instance_id) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/fog/compute/requests/aws/get_console_output.rb', line 33

def get_console_output(instance_id)
  response = Excon::Response.new
  if instance = @data[:instances][instance_id]
    response.status = 200
    response.body = {
      'instanceId'    => instance_id,
      'output'        => nil,
      'requestId'     => Fog::AWS::Mock.request_id,
      'timestamp'     => Time.now
    }
    response
  else;
    raise Fog::AWS::Compute::NotFound.new("The instance ID '#{instance_id}' does not exist")
  end
end

#import_key_pair(key_name, public_key_material) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/fog/compute/requests/aws/import_key_pair.rb', line 33

def import_key_pair(key_name, public_key_material)
  response = Excon::Response.new
  unless @data[:key_pairs][key_name]
    response.status = 200
    data = {
      'keyFingerprint'  => Fog::AWS::Mock.key_fingerprint,
      'keyName'         => key_name
    }
    @data[:key_pairs][key_name] = data
    response.body = {
      'requestId' => Fog::AWS::Mock.request_id
    }.merge!(data)
    response
  else
    raise Fog::AWS::Compute::Error.new("InvalidKeyPair.Duplicate => The keypair '#{key_name}' already exists.")
  end
end

#modify_image_attributes(image_id, attribute, operation_type, options = {}) ⇒ Object



32
33
34
# File 'lib/fog/compute/requests/aws/modify_image_attributes.rb', line 32

def modify_image_attributes(image_id, attribute, operation_type, options = {})
  Fog::Mock.not_implemented
end

#modify_snapshot_attribute(snapshot_id, attribute, operation_type, options = {}) ⇒ Object



31
32
33
# File 'lib/fog/compute/requests/aws/modify_snapshot_attribute.rb', line 31

def modify_snapshot_attribute(snapshot_id, attribute, operation_type, options = {})
  Fog::Mock.not_implemented
end

#reboot_instances(instance_id = []) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/fog/compute/requests/aws/reboot_instances.rb', line 29

def reboot_instances(instance_id = [])
  response = Excon::Response.new
  instance_id = [*instance_id]
  if (@data[:instances].keys & instance_id).length == instance_id.length
    for instance_id in instance_id
      @data[:instances][instance_id]['status'] = 'rebooting'
    end
    response.status = 200
    response.body = {
      'requestId' => Fog::AWS::Mock.request_id,
      'return'    => true
    }
    response
  else
    raise Fog::AWS::Compute::NotFound.new("The instance ID #{instance_id.inspect} does not exist")
  end
end

#register_image(name, description, location, block_devices = [], options = {}) ⇒ Object



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/fog/compute/requests/aws/register_image.rb', line 68

def register_image(name, description, location, block_devices=[], options={})
  response = Excon::Response.new
  if !name.empty?
    response.status = 200
    response.body = {
      'requestId' => Fog::AWS::Mock.request_id,
      'imageId' => Fog::AWS::Mock.image_id
    }
    response
  else
    message = 'MissingParameter => '
    if name.empty?
      message << 'The request must contain the parameter name'
    end
    raise Fog::AWS::Compute::Error.new(message)
  end
end

#release_address(public_ip) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/fog/compute/requests/aws/release_address.rb', line 26

def release_address(public_ip)
  response = Excon::Response.new
  if (address = @data[:addresses].delete(public_ip))
    response.status = 200
    response.body = {
      'requestId' => Fog::AWS::Mock.request_id,
      'return'    => true
    }
    response
  else
    raise Fog::AWS::Compute::Error.new("AuthFailure => The address '#{public_ip}' does not belong to you.")
  end
end

#revoke_security_group_ingress(options = {}) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/fog/compute/requests/aws/revoke_security_group_ingress.rb', line 37

def revoke_security_group_ingress(options = {})
  response = Excon::Response.new
  group = @data[:security_groups][options['GroupName']]
  if group
    if options['GroupName'] && options['SourceSecurityGroupName'] && options['SourceSecurityGroupOwnerId']
      group['ipPermissions'].delete_if {|permission|
        permission['groups'].first['groupName'] == options['GroupName']
      }
    else
      ingress = group['ipPermissions'].select {|permission|
        permission['fromPort']    == options['FromPort'] &&
        permission['ipProtocol']  == options['IpProtocol'] &&
        permission['toPort']      == options['ToPort'] &&
        (
          permission['ipRanges'].empty? ||
          (
            permission['ipRanges'].first &&
            permission['ipRanges'].first['cidrIp'] == options['CidrIp']
          )
        )
      }.first
      group['ipPermissions'].delete(ingress)
    end
    response.status = 200
    response.body = {
      'requestId' => Fog::AWS::Mock.request_id,
      'return'    => true
    }
    response
  else
    raise Fog::AWS::Compute::NotFound.new("The security group '#{options['GroupName']}' does not exist")
  end
end

#run_instances(image_id, min_count, max_count, options = {}) ⇒ Object



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
# File 'lib/fog/compute/requests/aws/run_instances.rb', line 113

def run_instances(image_id, min_count, max_count, options = {})
  response = Excon::Response.new
  response.status = 200

  group_set = [ (options['GroupId'] || 'default') ]
  instances_set = []
  reservation_id = Fog::AWS::Mock.reservation_id

  min_count.times do |i|
    instance_id = Fog::AWS::Mock.instance_id
    instance = {
      'amiLaunchIndex'      => i,
      'blockDeviceMapping'  => [],
      'clientToken'         => options['clientToken'],
      'dnsName'             => nil,
      'imageId'             => image_id,
      'instanceId'          => instance_id,
      'instanceState'       => { 'code' => 0, 'name' => 'pending' },
      'instanceType'        => options['InstanceType'] || 'm1.small',
      'kernelId'            => options['KernelId'] || Fog::AWS::Mock.kernel_id,
      # 'keyName'             => options['KeyName'],
      'launchTime'          => Time.now,
      'monitoring'          => { 'state' => options['Monitoring.Enabled'] || false },
      'placement'           => { 'availabilityZone' => options['Placement.AvailabilityZone'] || Fog::AWS::Mock.availability_zone },
      'privateDnsName'      => nil,
      'productCodes'        => [],
      'ramdiskId'           => options['RamdiskId'] || Fog::AWS::Mock.ramdisk_id,
      'reason'              => nil,
      'rootDeviceType'      => 'instance-store'
    }
    instances_set << instance
    @data[:instances][instance_id] = instance.merge({
      'architecture'        => 'i386',
      'groupSet'            => group_set,
      'ownerId'             => @owner_id,
      'privateIpAddress'    => nil,
      'reservationId'       => reservation_id,
      'stateReason'         => {},
      'tagSet'              => {}
    })
  end
  response.body = {
    'groupSet'      => group_set,
    'instancesSet'  => instances_set,
    'ownerId'       => @owner_id,
    'requestId'     => Fog::AWS::Mock.request_id,
    'reservationId' => reservation_id
  }
  response
end

#start_instances(instance_id) ⇒ Object



31
32
33
# File 'lib/fog/compute/requests/aws/start_instances.rb', line 31

def start_instances(instance_id)
  Fog::Mock.not_implemented
end

#stop_instances(instance_id) ⇒ Object



31
32
33
# File 'lib/fog/compute/requests/aws/stop_instances.rb', line 31

def stop_instances(instance_id)
  Fog::Mock.not_implemented
end

#terminate_instances(instance_id) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/fog/compute/requests/aws/terminate_instances.rb', line 38

def terminate_instances(instance_id)
  response = Excon::Response.new
  instance_id = [*instance_id]
  if (@data[:instances].keys & instance_id).length == instance_id.length
    response.body = {
      'requestId'     => Fog::AWS::Mock.request_id,
      'instancesSet'  => []
    }
    response.status = 200
    for id in instance_id
      instance = @data[:instances][id]
      @data[:deleted_at][id] = Time.now
      code = case instance['instanceState']['name']
      when 'pending'
        0
      when 'running'
        16
      when 'shutting-down'
        32
      when 'terminated'
        48
      when 'stopping'
        64
      when 'stopped'
        80
      end
      state = { 'name' => 'shutting-down', 'code' => 32}
      response.body['instancesSet'] << {
        'instanceId'    => id,
        'previousState' => instance['instanceState'],
        'currentState'  => state
      }
      instance['instanceState'] = state
    end

    describe_addresses.body['addressesSet'].each do |address|
      if instance_id.include?(address['instanceId'])
        disassociate_address(address['publicIp'])
      end
    end

    describe_volumes.body['volumeSet'].each do |volume|
      if volume['attachmentSet'].first && instance_id.include?(volume['attachmentSet'].first['instanceId'])
        detach_volume(volume['volumeId'])
      end
    end

    response
  else
    raise Fog::AWS::Compute::NotFound.new("The instance ID '#{instance_id}' does not exist")
  end
end