Class: Fog::AWS::EC2::Mock

Inherits:
Object
  • Object
show all
Includes:
Collections
Defined in:
lib/fog/aws/ec2.rb,
lib/fog/aws/requests/ec2/attach_volume.rb,
lib/fog/aws/requests/ec2/create_volume.rb,
lib/fog/aws/requests/ec2/delete_volume.rb,
lib/fog/aws/requests/ec2/detach_volume.rb,
lib/fog/aws/requests/ec2/run_instances.rb,
lib/fog/aws/requests/ec2/create_key_pair.rb,
lib/fog/aws/requests/ec2/create_snapshot.rb,
lib/fog/aws/requests/ec2/delete_key_pair.rb,
lib/fog/aws/requests/ec2/delete_snapshot.rb,
lib/fog/aws/requests/ec2/describe_images.rb,
lib/fog/aws/requests/ec2/release_address.rb,
lib/fog/aws/requests/ec2/allocate_address.rb,
lib/fog/aws/requests/ec2/describe_regions.rb,
lib/fog/aws/requests/ec2/describe_volumes.rb,
lib/fog/aws/requests/ec2/reboot_instances.rb,
lib/fog/aws/requests/ec2/associate_address.rb,
lib/fog/aws/requests/ec2/describe_addresses.rb,
lib/fog/aws/requests/ec2/describe_instances.rb,
lib/fog/aws/requests/ec2/describe_key_pairs.rb,
lib/fog/aws/requests/ec2/describe_snapshots.rb,
lib/fog/aws/requests/ec2/get_console_output.rb,
lib/fog/aws/requests/ec2/terminate_instances.rb,
lib/fog/aws/requests/ec2/disassociate_address.rb,
lib/fog/aws/requests/ec2/create_security_group.rb,
lib/fog/aws/requests/ec2/delete_security_group.rb,
lib/fog/aws/requests/ec2/modify_image_attributes.rb,
lib/fog/aws/requests/ec2/describe_security_groups.rb,
lib/fog/aws/requests/ec2/describe_availability_zones.rb,
lib/fog/aws/requests/ec2/describe_reserved_instances.rb,
lib/fog/aws/requests/ec2/revoke_security_group_ingress.rb,
lib/fog/aws/requests/ec2/authorize_security_group_ingress.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Collections

#addresses, #flavors, #images, #key_pairs, #security_groups, #servers, #snapshots, #volumes

Constructor Details

#initialize(options = {}) ⇒ Mock

Returns a new instance of Mock.



116
117
118
119
120
# File 'lib/fog/aws/ec2.rb', line 116

def initialize(options={})
  @aws_access_key_id = options[:aws_access_key_id]
  @data = self.class.data[@aws_access_key_id]
  @owner_id = @data[:owner_id]
end

Class Method Details

.dataObject



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

def self.data
  @data ||= Hash.new do |hash, key|
    owner_id = Fog::AWS::Mock.owner_id
    hash[key] = {
      :deleted_at => {},
      :addresses  => {},
      :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 => {}
    }
  end
end

.reset_data(keys = data.keys) ⇒ Object



110
111
112
113
114
# File 'lib/fog/aws/ec2.rb', line 110

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/aws/requests/ec2/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/aws/requests/ec2/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::EC2::NotFound.new("The instance ID '#{instance_id}' does not exist")
  elsif !address
    raise Fog::AWS::EC2::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/aws/requests/ec2/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::EC2::NotFound.new("The instance ID '#{instance_id}' does not exist.")
    elsif !volume
      raise Fog::AWS::EC2::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::EC2::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/aws/requests/ec2/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::EC2::NotFound.new("The security group '#{options['GroupName']}' does not exist")
  end
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/aws/requests/ec2/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::EC2::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/aws/requests/ec2/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::EC2::Error.new("InvalidGroup.Duplicate => The security group '#{name}' already exists")
  end
end

#create_snapshot(volume_id, description = nil) ⇒ Object



35
36
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/aws/requests/ec2/create_snapshot.rb', line 35

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)
  else
    response.status = 400
    raise(Excon::Errors.status_error({:expects => 200}, response))
  end
  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
# File 'lib/fog/aws/requests/ec2/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',
      '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/aws/requests/ec2/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/aws/requests/ec2/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::EC2::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/aws/requests/ec2/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::EC2::NotFound.new("The snapshot '#{snapshot_id}' does not exist.")
  end
end

#delete_volume(volume_id) ⇒ Object



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

def delete_volume(volume_id)
  response = Excon::Response.new
  if volume = @data[:volumes][volume_id]
    @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::EC2::NotFound.new("The volume '#{volume_id}' does not exist.")
  end
end

#describe_addresses(public_ip = []) ⇒ Object



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

def describe_addresses(public_ip = [])
  response = Excon::Response.new
  public_ip = [*public_ip]
  if public_ip != []
    addresses_set = @data[:addresses].reject {|key, value| !public_ip.include?(key)}.values
  else
    addresses_set = @data[:addresses].values
  end
  if public_ip.length == 0 || public_ip.length == addresses_set.length
    response.status = 200
    response.body = {
      'requestId'     => Fog::AWS::Mock.request_id,
      'addressesSet'  => addresses_set
    }
    response
  else
    raise Fog::AWS::EC2::NotFound.new("Address #{public_ip.inspect} not found.")
  end
end

#describe_availability_zones(zone_name = []) ⇒ Object



34
35
36
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/aws/requests/ec2/describe_availability_zones.rb', line 34

def describe_availability_zones(zone_name = [])
  response = Excon::Response.new
  zone_name = [*zone_name]
  zones = {
    'us-east-1a' => {"zoneName"=>"us-east-1a", "regionName"=>"us-east-1", "zoneState"=>"available"}, 
    'us-east-1b' => {"zoneName"=>"us-east-1b", "regionName"=>"us-east-1", "zoneState"=>"available"}, 
    'us-east-1c' => {"zoneName"=>"us-east-1c", "regionName"=>"us-east-1", "zoneState"=>"available"}, 
    'us-east-1d' => {"zoneName"=>"us-east-1d", "regionName"=>"us-east-1", "zoneState"=>"available"}
  }
  if zone_name != []
    availability_zone_info = zones.reject {|key, value| !zone_name.include?(key)}.values
  else
    availability_zone_info = zones.values
  end

  if zone_name.length == 0 || zone_name.length == availability_zone_info.length
    response.status = 200
    response.body = {
      'requestId'             => Fog::AWS::Mock.request_id,
      'availabilityZoneInfo'  => availability_zone_info
    }
    response
  else
    raise Fog::AWS::EC2::Error.new("InvalidParameterValue => Invalid availability zone: #{zone_name.inspect}")
  end
end

#describe_images(options = {}) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/fog/aws/requests/ec2/describe_images.rb', line 48

def describe_images(options = {})
  response = Excon::Response.new
  images = []

  (rand(101 + 100)).times do
    images << Fog::AWS::Mock.image
  end

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

#describe_instances(instance_id = []) ⇒ Object



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
116
117
118
119
120
121
122
123
124
# File 'lib/fog/aws/requests/ec2/describe_instances.rb', line 66

def describe_instances(instance_id = [])
  response = Excon::Response.new
  instance_id = [*instance_id]
  if instance_id != []
    instance_set = @data[:instances].reject {|key,value| !instance_id.include?(key)}.values
  else
    instance_set = @data[:instances].values
  end

  if instance_id.length == 0 || instance_id.length == instance_set.length
    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' => 16, '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', 'dnsName', 'imageId', 'instanceId', 'instanceState', 'instanceType', 'ipAddress', 'kernelId', 'keyName', 'launchTime', 'monitoring', 'placement', 'privateDnsName', 'privateIpAddress', 'productCodes', 'ramdiskId', 'reason', 'rootDeviceType'].include?(key)}
      end
    end

    response.body = {
      'requestId'       => Fog::AWS::Mock.request_id,
      'reservationSet' => reservation_set.values
    }
    response
  else
    raise Fog::AWS::EC2::NotFound.new("The instance ID #{instance_id.inspect} does not exist")
  end
end

#describe_key_pairs(key_name = []) ⇒ Object



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

def describe_key_pairs(key_name = [])
  response = Excon::Response.new
  key_name = [*key_name]
  if key_name != []
    key_set = @data[:key_pairs].reject {|key, value| !key_name.include?(key)}.values
  else
    key_set = @data[:key_pairs].values
  end
  if key_name.length == 0 || key_name.length == key_set.length
    response.status = 200
    response.body = {
      'requestId' => Fog::AWS::Mock.request_id,
      'keySet'    => key_set.map do |key|
        key.reject {|key,value| !['keyFingerprint', 'keyName'].include?(key)}
      end
    }
    response
  else
    raise Fog::AWS::EC2::NotFound.new("The key pair #{key_name.inspect} does not exist")
  end
end

#describe_regions(region_name = []) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/fog/aws/requests/ec2/describe_regions.rb', line 33

def describe_regions(region_name = [])
  response = Excon::Response.new
  region_name = [*region_name]
  regions = {
    'eu-west-1' => {"regionName"=>"eu-west-1", "regionEndpoint"=>"eu-west-1.ec2.amazonaws.com"},
    'us-east-1' => {"regionName"=>"us-east-1", "regionEndpoint"=>"us-east-1.ec2.amazonaws.com"}
  }
  if region_name != []
    region_info = regions.reject {|key, value| !region_name.include?(key)}.values
  else
    region_info = regions.values
  end

  if region_name.length == 0 || region_name.length == region_info.length
    response.status = 200
    response.body = {
      'requestId'   => Fog::AWS::Mock.request_id,
      'regionInfo'  => region_info
    }
    response
  else
    raise Fog::AWS::EC2::Error.new("InvalidParameterValue => Invalid region: #{region_name.inspect}")
  end
end

#describe_reserved_instances(reserved_instances_id = {}) ⇒ Object



41
42
43
# File 'lib/fog/aws/requests/ec2/describe_reserved_instances.rb', line 41

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

#describe_security_groups(group_name = []) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/fog/aws/requests/ec2/describe_security_groups.rb', line 43

def describe_security_groups(group_name = [])
  response = Excon::Response.new
  group_name = [*group_name]
  if group_name != []
    security_group_info = @data[:security_groups].reject {|key, value| !group_name.include?(key)}.values
  else
    security_group_info = @data[:security_groups].values
  end
  if group_name.length == 0 || group_name.length == security_group_info.length
    response.status = 200
    response.body = {
      'requestId'         => Fog::AWS::Mock.request_id,
      'securityGroupInfo' => security_group_info
    }
    response
  else
    raise Fog::AWS::EC2::NotFound.new("The security group #{group_name.inspect} does not exist")
  end
end

#describe_snapshots(snapshot_id = []) ⇒ Object



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
# File 'lib/fog/aws/requests/ec2/describe_snapshots.rb', line 40

def describe_snapshots(snapshot_id = [])
  response = Excon::Response.new
  snapshot_id = [*snapshot_id]
  if snapshot_id != []
    snapshot_set = @data[:snapshots].reject {|key,value| !snapshot_id.include?(key)}.values
  else
    snapshot_set = @data[:snapshots].values
  end

  if snapshot_id.length == 0 || snapshot_id.length == snapshot_set.length
    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
  else
    raise Fog::AWS::EC2::NotFound.new("The snapshot #{snapshot_id.inspect} does not exist.")
  end
end

#describe_volumes(volume_id = []) ⇒ Object



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/aws/requests/ec2/describe_volumes.rb', line 42

def describe_volumes(volume_id = [])
  response = Excon::Response.new
  volume_id = [*volume_id]
  if volume_id != []
    volume_set = @data[:volumes].reject {|key,value| !volume_id.include?(key)}.values
  else
    volume_set = @data[:volumes].values
  end

  if volume_id.length == 0 || volume_id.length == volume_set.length
    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
  else
    raise Fog::AWS::EC2::NotFound.new("The volume #{volume_id.inspect} does not exist.")
  end
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/aws/requests/ec2/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::EC2::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/aws/requests/ec2/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::EC2::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/aws/requests/ec2/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::EC2::NotFound.new("The instance ID '#{instance_id}' does not exist")
  end
end

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



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

def modify_image_attributes(image_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/aws/requests/ec2/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::EC2::NotFound.new("The instance ID #{instance_id.inspect} does not exist")
  end
end

#release_address(public_ip) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/fog/aws/requests/ec2/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::EC2::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/aws/requests/ec2/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::EC2::NotFound.new("The security group '#{options['GroupName']}' does not exist")
  end
end

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



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

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'  => [],
      '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,
    })
  end
  response.body = {
    'groupSet'      => group_set,
    'instancesSet'  => instances_set,
    'ownerId'       => @owner_id,
    'requestId'     => Fog::AWS::Mock.request_id,
    'reservationId' => reservation_id
  }
  response
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
# File 'lib/fog/aws/requests/ec2/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'
        64
      when 'rebooting'
        128
      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::EC2::NotFound.new("The instance ID '#{instance_id}' does not exist")
  end
end