PageRenderTime 61ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/boto-2.5.2/boto/ec2/instance.py

#
Python | 480 lines | 363 code | 9 blank | 108 comment | 16 complexity | 2d1a514d237c9deab72d44caabe95229 MD5 | raw file
  1. # Copyright (c) 2006-2010 Mitch Garnaat http://garnaat.org/
  2. # Copyright (c) 2010, Eucalyptus Systems, Inc.
  3. #
  4. # Permission is hereby granted, free of charge, to any person obtaining a
  5. # copy of this software and associated documentation files (the
  6. # "Software"), to deal in the Software without restriction, including
  7. # without limitation the rights to use, copy, modify, merge, publish, dis-
  8. # tribute, sublicense, and/or sell copies of the Software, and to permit
  9. # persons to whom the Software is furnished to do so, subject to the fol-
  10. # lowing conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included
  13. # in all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  16. # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
  17. # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
  18. # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  19. # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  21. # IN THE SOFTWARE.
  22. """
  23. Represents an EC2 Instance
  24. """
  25. import boto
  26. from boto.ec2.ec2object import EC2Object, TaggedEC2Object
  27. from boto.resultset import ResultSet
  28. from boto.ec2.address import Address
  29. from boto.ec2.blockdevicemapping import BlockDeviceMapping
  30. from boto.ec2.image import ProductCodes
  31. from boto.ec2.networkinterface import NetworkInterface
  32. from boto.ec2.group import Group
  33. import base64
  34. class Reservation(EC2Object):
  35. """
  36. Represents a Reservation response object.
  37. :ivar id: The unique ID of the Reservation.
  38. :ivar owner_id: The unique ID of the owner of the Reservation.
  39. :ivar groups: A list of Group objects representing the security
  40. groups associated with launched instances.
  41. :ivar instances: A list of Instance objects launched in this
  42. Reservation.
  43. """
  44. def __init__(self, connection=None):
  45. EC2Object.__init__(self, connection)
  46. self.id = None
  47. self.owner_id = None
  48. self.groups = []
  49. self.instances = []
  50. def __repr__(self):
  51. return 'Reservation:%s' % self.id
  52. def startElement(self, name, attrs, connection):
  53. if name == 'instancesSet':
  54. self.instances = ResultSet([('item', Instance)])
  55. return self.instances
  56. elif name == 'groupSet':
  57. self.groups = ResultSet([('item', Group)])
  58. return self.groups
  59. else:
  60. return None
  61. def endElement(self, name, value, connection):
  62. if name == 'reservationId':
  63. self.id = value
  64. elif name == 'ownerId':
  65. self.owner_id = value
  66. else:
  67. setattr(self, name, value)
  68. def stop_all(self):
  69. for instance in self.instances:
  70. instance.stop()
  71. class Instance(TaggedEC2Object):
  72. """
  73. Represents an instance.
  74. :ivar id: The unique ID of the Instance.
  75. :ivar groups: A list of Group objects representing the security
  76. groups associated with the instance.
  77. :ivar public_dns_name: The public dns name of the instance.
  78. :ivar private_dns_name: The private dns name of the instance.
  79. :ivar state: The string representation of the instances current state.
  80. :ivar state_code: An integer representation of the instances current state.
  81. :ivar key_name: The name of the SSH key associated with the instance.
  82. :ivar instance_type: The type of instance (e.g. m1.small).
  83. :ivar launch_time: The time the instance was launched.
  84. :ivar image_id: The ID of the AMI used to launch this instance.
  85. :ivar placement: The availability zone in which the instance is running.
  86. :ivar kernel: The kernel associated with the instance.
  87. :ivar ramdisk: The ramdisk associated with the instance.
  88. :ivar architecture: The architecture of the image (i386|x86_64).
  89. :ivar hypervisor: The hypervisor used.
  90. :ivar virtualization_type: The type of virtualization used.
  91. :ivar product_codes: A list of product codes associated with this instance.
  92. :ivar ami_launch_index: This instances position within it's launch group.
  93. :ivar monitored: A boolean indicating whether monitoring is enabled or not.
  94. :ivar spot_instance_request_id: The ID of the spot instance request
  95. if this is a spot instance.
  96. :ivar subnet_id: The VPC Subnet ID, if running in VPC.
  97. :ivar vpc_id: The VPC ID, if running in VPC.
  98. :ivar private_ip_address: The private IP address of the instance.
  99. :ivar ip_address: The public IP address of the instance.
  100. :ivar platform: Platform of the instance (e.g. Windows)
  101. :ivar root_device_name: The name of the root device.
  102. :ivar root_device_type: The root device type (ebs|instance-store).
  103. :ivar block_device_mapping: The Block Device Mapping for the instance.
  104. :ivar state_reason: The reason for the most recent state transition.
  105. :ivar groups: List of security Groups associated with the instance.
  106. :ivar interfaces: List of Elastic Network Interfaces associated with
  107. this instance.
  108. """
  109. def __init__(self, connection=None):
  110. TaggedEC2Object.__init__(self, connection)
  111. self.id = None
  112. self.dns_name = None
  113. self.public_dns_name = None
  114. self.private_dns_name = None
  115. self.state = None
  116. self.state_code = None
  117. self.key_name = None
  118. self.shutdown_state = None
  119. self.previous_state = None
  120. self.instance_type = None
  121. self.launch_time = None
  122. self.image_id = None
  123. self.placement = None
  124. self.kernel = None
  125. self.ramdisk = None
  126. self.product_codes = ProductCodes()
  127. self.ami_launch_index = None
  128. self.monitored = False
  129. self.spot_instance_request_id = None
  130. self.subnet_id = None
  131. self.vpc_id = None
  132. self.private_ip_address = None
  133. self.ip_address = None
  134. self.requester_id = None
  135. self._in_monitoring_element = False
  136. self.persistent = False
  137. self.root_device_name = None
  138. self.root_device_type = None
  139. self.block_device_mapping = None
  140. self.state_reason = None
  141. self.group_name = None
  142. self.client_token = None
  143. self.eventsSet = None
  144. self.groups = []
  145. self.platform = None
  146. self.interfaces = []
  147. self.hypervisor = None
  148. self.virtualization_type = None
  149. self.architecture = None
  150. def __repr__(self):
  151. return 'Instance:%s' % self.id
  152. def startElement(self, name, attrs, connection):
  153. retval = TaggedEC2Object.startElement(self, name, attrs, connection)
  154. if retval is not None:
  155. return retval
  156. if name == 'monitoring':
  157. self._in_monitoring_element = True
  158. elif name == 'blockDeviceMapping':
  159. self.block_device_mapping = BlockDeviceMapping()
  160. return self.block_device_mapping
  161. elif name == 'productCodes':
  162. return self.product_codes
  163. elif name == 'stateReason':
  164. self.state_reason = SubParse('stateReason')
  165. return self.state_reason
  166. elif name == 'groupSet':
  167. self.groups = ResultSet([('item', Group)])
  168. return self.groups
  169. elif name == "eventsSet":
  170. self.eventsSet = SubParse('eventsSet')
  171. return self.eventsSet
  172. elif name == 'networkInterfaceSet':
  173. self.interfaces = ResultSet([('item', NetworkInterface)])
  174. elif name == 'iamInstanceProfile':
  175. self.instance_profile = SubParse('iamInstanceProfile')
  176. return self.instance_profile
  177. return None
  178. def endElement(self, name, value, connection):
  179. if name == 'instanceId':
  180. self.id = value
  181. elif name == 'imageId':
  182. self.image_id = value
  183. elif name == 'dnsName' or name == 'publicDnsName':
  184. self.dns_name = value # backwards compatibility
  185. self.public_dns_name = value
  186. elif name == 'privateDnsName':
  187. self.private_dns_name = value
  188. elif name == 'keyName':
  189. self.key_name = value
  190. elif name == 'amiLaunchIndex':
  191. self.ami_launch_index = value
  192. elif name == 'shutdownState':
  193. self.shutdown_state = value
  194. elif name == 'previousState':
  195. self.previous_state = value
  196. elif name == 'name':
  197. self.state = value
  198. elif name == 'code':
  199. try:
  200. self.state_code = int(value)
  201. except ValueError:
  202. boto.log.warning('Error converting code (%s) to int' % value)
  203. self.state_code = value
  204. elif name == 'instanceType':
  205. self.instance_type = value
  206. elif name == 'rootDeviceName':
  207. self.root_device_name = value
  208. elif name == 'rootDeviceType':
  209. self.root_device_type = value
  210. elif name == 'launchTime':
  211. self.launch_time = value
  212. elif name == 'availabilityZone':
  213. self.placement = value
  214. elif name == 'platform':
  215. self.platform = value
  216. elif name == 'placement':
  217. pass
  218. elif name == 'kernelId':
  219. self.kernel = value
  220. elif name == 'ramdiskId':
  221. self.ramdisk = value
  222. elif name == 'state':
  223. if self._in_monitoring_element:
  224. if value == 'enabled':
  225. self.monitored = True
  226. self._in_monitoring_element = False
  227. elif name == 'spotInstanceRequestId':
  228. self.spot_instance_request_id = value
  229. elif name == 'subnetId':
  230. self.subnet_id = value
  231. elif name == 'vpcId':
  232. self.vpc_id = value
  233. elif name == 'privateIpAddress':
  234. self.private_ip_address = value
  235. elif name == 'ipAddress':
  236. self.ip_address = value
  237. elif name == 'requesterId':
  238. self.requester_id = value
  239. elif name == 'persistent':
  240. if value == 'true':
  241. self.persistent = True
  242. else:
  243. self.persistent = False
  244. elif name == 'groupName':
  245. if self._in_monitoring_element:
  246. self.group_name = value
  247. elif name == 'clientToken':
  248. self.client_token = value
  249. elif name == "eventsSet":
  250. self.events = value
  251. elif name == 'hypervisor':
  252. self.hypervisor = value
  253. elif name == 'virtualizationType':
  254. self.virtualization_type = value
  255. elif name == 'architecture':
  256. self.architecture = value
  257. else:
  258. setattr(self, name, value)
  259. def _update(self, updated):
  260. self.__dict__.update(updated.__dict__)
  261. def update(self, validate=False):
  262. """
  263. Update the instance's state information by making a call to fetch
  264. the current instance attributes from the service.
  265. :type validate: bool
  266. :param validate: By default, if EC2 returns no data about the
  267. instance the update method returns quietly. If
  268. the validate param is True, however, it will
  269. raise a ValueError exception if no data is
  270. returned from EC2.
  271. """
  272. rs = self.connection.get_all_instances([self.id])
  273. if len(rs) > 0:
  274. r = rs[0]
  275. for i in r.instances:
  276. if i.id == self.id:
  277. self._update(i)
  278. elif validate:
  279. raise ValueError('%s is not a valid Instance ID' % self.id)
  280. return self.state
  281. def terminate(self):
  282. """
  283. Terminate the instance
  284. """
  285. rs = self.connection.terminate_instances([self.id])
  286. if len(rs) > 0:
  287. self._update(rs[0])
  288. def stop(self, force=False):
  289. """
  290. Stop the instance
  291. :type force: bool
  292. :param force: Forces the instance to stop
  293. :rtype: list
  294. :return: A list of the instances stopped
  295. """
  296. rs = self.connection.stop_instances([self.id], force)
  297. if len(rs) > 0:
  298. self._update(rs[0])
  299. def start(self):
  300. """
  301. Start the instance.
  302. """
  303. rs = self.connection.start_instances([self.id])
  304. if len(rs) > 0:
  305. self._update(rs[0])
  306. def reboot(self):
  307. return self.connection.reboot_instances([self.id])
  308. def get_console_output(self):
  309. """
  310. Retrieves the console output for the instance.
  311. :rtype: :class:`boto.ec2.instance.ConsoleOutput`
  312. :return: The console output as a ConsoleOutput object
  313. """
  314. return self.connection.get_console_output(self.id)
  315. def confirm_product(self, product_code):
  316. return self.connection.confirm_product_instance(self.id, product_code)
  317. def use_ip(self, ip_address):
  318. if isinstance(ip_address, Address):
  319. ip_address = ip_address.public_ip
  320. return self.connection.associate_address(self.id, ip_address)
  321. def monitor(self):
  322. return self.connection.monitor_instance(self.id)
  323. def unmonitor(self):
  324. return self.connection.unmonitor_instance(self.id)
  325. def get_attribute(self, attribute):
  326. """
  327. Gets an attribute from this instance.
  328. :type attribute: string
  329. :param attribute: The attribute you need information about
  330. Valid choices are:
  331. instanceType|kernel|ramdisk|userData|
  332. disableApiTermination|
  333. instanceInitiatedShutdownBehavior|
  334. rootDeviceName|blockDeviceMapping
  335. sourceDestCheck|groupSet
  336. :rtype: :class:`boto.ec2.image.InstanceAttribute`
  337. :return: An InstanceAttribute object representing the value of the
  338. attribute requested
  339. """
  340. return self.connection.get_instance_attribute(self.id, attribute)
  341. def modify_attribute(self, attribute, value):
  342. """
  343. Changes an attribute of this instance
  344. :type attribute: string
  345. :param attribute: The attribute you wish to change.
  346. * AttributeName - Expected value (default)
  347. * InstanceType - A valid instance type (m1.small)
  348. * Kernel - Kernel ID (None)
  349. * Ramdisk - Ramdisk ID (None)
  350. * UserData - Base64 encoded String (None)
  351. * DisableApiTermination - Boolean (true)
  352. * InstanceInitiatedShutdownBehavior - stop|terminate
  353. * RootDeviceName - device name (None)
  354. * SourceDestCheck - Boolean (true)
  355. * GroupSet - Set of Security Groups or IDs
  356. :type value: string
  357. :param value: The new value for the attribute
  358. :rtype: bool
  359. :return: Whether the operation succeeded or not
  360. """
  361. return self.connection.modify_instance_attribute(self.id, attribute,
  362. value)
  363. def reset_attribute(self, attribute):
  364. """
  365. Resets an attribute of this instance to its default value.
  366. :type attribute: string
  367. :param attribute: The attribute to reset. Valid values are:
  368. kernel|ramdisk
  369. :rtype: bool
  370. :return: Whether the operation succeeded or not
  371. """
  372. return self.connection.reset_instance_attribute(self.id, attribute)
  373. class ConsoleOutput:
  374. def __init__(self, parent=None):
  375. self.parent = parent
  376. self.instance_id = None
  377. self.timestamp = None
  378. self.output = None
  379. def startElement(self, name, attrs, connection):
  380. return None
  381. def endElement(self, name, value, connection):
  382. if name == 'instanceId':
  383. self.instance_id = value
  384. elif name == 'timestamp':
  385. self.timestamp = value
  386. elif name == 'output':
  387. self.output = base64.b64decode(value)
  388. else:
  389. setattr(self, name, value)
  390. class InstanceAttribute(dict):
  391. ValidValues = ['instanceType', 'kernel', 'ramdisk', 'userData',
  392. 'disableApiTermination', 'instanceInitiatedShutdownBehavior',
  393. 'rootDeviceName', 'blockDeviceMapping', 'sourceDestCheck',
  394. 'groupSet']
  395. def __init__(self, parent=None):
  396. dict.__init__(self)
  397. self.instance_id = None
  398. self.request_id = None
  399. self._current_value = None
  400. def startElement(self, name, attrs, connection):
  401. if name == 'blockDeviceMapping':
  402. self[name] = BlockDeviceMapping()
  403. return self[name]
  404. elif name == 'groupSet':
  405. self[name] = ResultSet([('item', Group)])
  406. return self[name]
  407. else:
  408. return None
  409. def endElement(self, name, value, connection):
  410. if name == 'instanceId':
  411. self.instance_id = value
  412. elif name == 'requestId':
  413. self.request_id = value
  414. elif name == 'value':
  415. self._current_value = value
  416. elif name in self.ValidValues:
  417. self[name] = self._current_value
  418. class SubParse(dict):
  419. def __init__(self, section, parent=None):
  420. dict.__init__(self)
  421. self.section = section
  422. def startElement(self, name, attrs, connection):
  423. return None
  424. def endElement(self, name, value, connection):
  425. if name != self.section:
  426. self[name] = value