You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1098 lines
36 KiB

4 years ago
  1. # Copyright (c) 2006-2012 Mitch Garnaat http://garnaat.org/
  2. # Copyright (c) 2010, Eucalyptus Systems, Inc.
  3. # Copyright (c) 2012 Amazon.com, Inc. or its affiliates.
  4. # All rights reserved.
  5. #
  6. # Permission is hereby granted, free of charge, to any person obtaining a
  7. # copy of this software and associated documentation files (the
  8. # "Software"), to deal in the Software without restriction, including
  9. # without limitation the rights to use, copy, modify, merge, publish, dis-
  10. # tribute, sublicense, and/or sell copies of the Software, and to permit
  11. # persons to whom the Software is furnished to do so, subject to the fol-
  12. # lowing conditions:
  13. #
  14. # The above copyright notice and this permission notice shall be included
  15. # in all copies or substantial portions of the Software.
  16. #
  17. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  18. # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
  19. # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
  20. # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  21. # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  23. # IN THE SOFTWARE.
  24. #
  25. # Parts of this code were copied or derived from sample code supplied by AWS.
  26. # The following notice applies to that code.
  27. #
  28. # This software code is made available "AS IS" without warranties of any
  29. # kind. You may copy, display, modify and redistribute the software
  30. # code either by itself or as incorporated into your code; provided that
  31. # you do not remove any proprietary notices. Your use of this software
  32. # code is at your own risk and you waive any claim against Amazon
  33. # Digital Services, Inc. or its affiliates with respect to your use of
  34. # this software code. (c) 2006 Amazon Digital Services, Inc. or its
  35. # affiliates.
  36. """
  37. Some handy utility functions used by several classes.
  38. """
  39. import subprocess
  40. import time
  41. import logging.handlers
  42. import boto
  43. import boto.provider
  44. import tempfile
  45. import random
  46. import smtplib
  47. import datetime
  48. import re
  49. import email.mime.multipart
  50. import email.mime.base
  51. import email.mime.text
  52. import email.utils
  53. import email.encoders
  54. import gzip
  55. import threading
  56. import locale
  57. from boto.compat import six, StringIO, urllib, encodebytes
  58. from contextlib import contextmanager
  59. from hashlib import md5, sha512
  60. _hashfn = sha512
  61. from boto.compat import json
  62. try:
  63. from boto.compat.json import JSONDecodeError
  64. except ImportError:
  65. JSONDecodeError = ValueError
  66. # List of Query String Arguments of Interest
  67. qsa_of_interest = ['acl', 'cors', 'defaultObjectAcl', 'location', 'logging',
  68. 'partNumber', 'policy', 'requestPayment', 'torrent',
  69. 'versioning', 'versionId', 'versions', 'website',
  70. 'uploads', 'uploadId', 'response-content-type',
  71. 'response-content-language', 'response-expires',
  72. 'response-cache-control', 'response-content-disposition',
  73. 'response-content-encoding', 'delete', 'lifecycle',
  74. 'tagging', 'restore',
  75. # storageClass is a QSA for buckets in Google Cloud Storage.
  76. # (StorageClass is associated to individual keys in S3, but
  77. # having it listed here should cause no problems because
  78. # GET bucket?storageClass is not part of the S3 API.)
  79. 'storageClass',
  80. # websiteConfig is a QSA for buckets in Google Cloud
  81. # Storage.
  82. 'websiteConfig',
  83. # compose is a QSA for objects in Google Cloud Storage.
  84. 'compose',
  85. # billing is a QSA for buckets in Google Cloud Storage.
  86. 'billing',
  87. # userProject is a QSA for requests in Google Cloud Storage.
  88. 'userProject',
  89. # encryptionConfig is a QSA for requests in Google Cloud
  90. # Storage.
  91. 'encryptionConfig']
  92. _first_cap_regex = re.compile('(.)([A-Z][a-z]+)')
  93. _number_cap_regex = re.compile('([a-z])([0-9]+)')
  94. _end_cap_regex = re.compile('([a-z0-9])([A-Z])')
  95. def unquote_v(nv):
  96. if len(nv) == 1:
  97. return nv
  98. else:
  99. return (nv[0], urllib.parse.unquote(nv[1]))
  100. def canonical_string(method, path, headers, expires=None,
  101. provider=None):
  102. """
  103. Generates the aws canonical string for the given parameters
  104. """
  105. if not provider:
  106. provider = boto.provider.get_default()
  107. interesting_headers = {}
  108. for key in headers:
  109. lk = key.lower()
  110. if headers[key] is not None and \
  111. (lk in ['content-md5', 'content-type', 'date'] or
  112. lk.startswith(provider.header_prefix)):
  113. interesting_headers[lk] = str(headers[key]).strip()
  114. # these keys get empty strings if they don't exist
  115. if 'content-type' not in interesting_headers:
  116. interesting_headers['content-type'] = ''
  117. if 'content-md5' not in interesting_headers:
  118. interesting_headers['content-md5'] = ''
  119. # just in case someone used this. it's not necessary in this lib.
  120. if provider.date_header in interesting_headers:
  121. interesting_headers['date'] = ''
  122. # if you're using expires for query string auth, then it trumps date
  123. # (and provider.date_header)
  124. if expires:
  125. interesting_headers['date'] = str(expires)
  126. sorted_header_keys = sorted(interesting_headers.keys())
  127. buf = "%s\n" % method
  128. for key in sorted_header_keys:
  129. val = interesting_headers[key]
  130. if key.startswith(provider.header_prefix):
  131. buf += "%s:%s\n" % (key, val)
  132. else:
  133. buf += "%s\n" % val
  134. # don't include anything after the first ? in the resource...
  135. # unless it is one of the QSA of interest, defined above
  136. t = path.split('?')
  137. buf += t[0]
  138. if len(t) > 1:
  139. qsa = t[1].split('&')
  140. qsa = [a.split('=', 1) for a in qsa]
  141. qsa = [unquote_v(a) for a in qsa if a[0] in qsa_of_interest]
  142. if len(qsa) > 0:
  143. qsa.sort(key=lambda x: x[0])
  144. qsa = ['='.join(a) for a in qsa]
  145. buf += '?'
  146. buf += '&'.join(qsa)
  147. return buf
  148. def merge_meta(headers, metadata, provider=None):
  149. if not provider:
  150. provider = boto.provider.get_default()
  151. metadata_prefix = provider.metadata_prefix
  152. final_headers = headers.copy()
  153. for k in metadata.keys():
  154. if k.lower() in boto.s3.key.Key.base_user_settable_fields:
  155. final_headers[k] = metadata[k]
  156. else:
  157. final_headers[metadata_prefix + k] = metadata[k]
  158. return final_headers
  159. def get_aws_metadata(headers, provider=None):
  160. if not provider:
  161. provider = boto.provider.get_default()
  162. metadata_prefix = provider.metadata_prefix
  163. metadata = {}
  164. for hkey in headers.keys():
  165. if hkey.lower().startswith(metadata_prefix):
  166. val = urllib.parse.unquote(headers[hkey])
  167. if isinstance(val, bytes):
  168. try:
  169. val = val.decode('utf-8')
  170. except UnicodeDecodeError:
  171. # Just leave the value as-is
  172. pass
  173. metadata[hkey[len(metadata_prefix):]] = val
  174. del headers[hkey]
  175. return metadata
  176. def retry_url(url, retry_on_404=True, num_retries=10, timeout=None):
  177. """
  178. Retry a url. This is specifically used for accessing the metadata
  179. service on an instance. Since this address should never be proxied
  180. (for security reasons), we create a ProxyHandler with a NULL
  181. dictionary to override any proxy settings in the environment.
  182. """
  183. for i in range(0, num_retries):
  184. try:
  185. proxy_handler = urllib.request.ProxyHandler({})
  186. opener = urllib.request.build_opener(proxy_handler)
  187. req = urllib.request.Request(url)
  188. r = opener.open(req, timeout=timeout)
  189. result = r.read()
  190. if(not isinstance(result, six.string_types) and
  191. hasattr(result, 'decode')):
  192. result = result.decode('utf-8')
  193. return result
  194. except urllib.error.HTTPError as e:
  195. code = e.getcode()
  196. if code == 404 and not retry_on_404:
  197. return ''
  198. except Exception as e:
  199. boto.log.exception('Caught exception reading instance data')
  200. # If not on the last iteration of the loop then sleep.
  201. if i + 1 != num_retries:
  202. boto.log.debug('Sleeping before retrying')
  203. time.sleep(min(2 ** i,
  204. boto.config.get('Boto', 'max_retry_delay', 60)))
  205. boto.log.error('Unable to read instance data, giving up')
  206. return ''
  207. def _get_instance_metadata(url, num_retries, timeout=None):
  208. return LazyLoadMetadata(url, num_retries, timeout)
  209. class LazyLoadMetadata(dict):
  210. def __init__(self, url, num_retries, timeout=None):
  211. self._url = url
  212. self._num_retries = num_retries
  213. self._leaves = {}
  214. self._dicts = []
  215. self._timeout = timeout
  216. data = boto.utils.retry_url(self._url, num_retries=self._num_retries, timeout=self._timeout)
  217. if data:
  218. fields = data.split('\n')
  219. for field in fields:
  220. if field.endswith('/'):
  221. key = field[0:-1]
  222. self._dicts.append(key)
  223. else:
  224. p = field.find('=')
  225. if p > 0:
  226. key = field[p + 1:]
  227. resource = field[0:p] + '/openssh-key'
  228. else:
  229. key = resource = field
  230. self._leaves[key] = resource
  231. self[key] = None
  232. def _materialize(self):
  233. for key in self:
  234. self[key]
  235. def __getitem__(self, key):
  236. if key not in self:
  237. # allow dict to throw the KeyError
  238. return super(LazyLoadMetadata, self).__getitem__(key)
  239. # already loaded
  240. val = super(LazyLoadMetadata, self).__getitem__(key)
  241. if val is not None:
  242. return val
  243. if key in self._leaves:
  244. resource = self._leaves[key]
  245. last_exception = None
  246. for i in range(0, self._num_retries):
  247. try:
  248. val = boto.utils.retry_url(
  249. self._url + urllib.parse.quote(resource,
  250. safe="/:"),
  251. num_retries=self._num_retries,
  252. timeout=self._timeout)
  253. if val and val[0] == '{':
  254. val = json.loads(val)
  255. break
  256. else:
  257. p = val.find('\n')
  258. if p > 0:
  259. val = val.split('\n')
  260. break
  261. except JSONDecodeError as e:
  262. boto.log.debug(
  263. "encountered '%s' exception: %s" % (
  264. e.__class__.__name__, e))
  265. boto.log.debug(
  266. 'corrupted JSON data found: %s' % val)
  267. last_exception = e
  268. except Exception as e:
  269. boto.log.debug("encountered unretryable" +
  270. " '%s' exception, re-raising" % (
  271. e.__class__.__name__))
  272. last_exception = e
  273. raise
  274. boto.log.error("Caught exception reading meta data" +
  275. " for the '%s' try" % (i + 1))
  276. if i + 1 != self._num_retries:
  277. next_sleep = min(
  278. random.random() * 2 ** i,
  279. boto.config.get('Boto', 'max_retry_delay', 60))
  280. time.sleep(next_sleep)
  281. else:
  282. boto.log.error('Unable to read meta data, giving up')
  283. boto.log.error(
  284. "encountered '%s' exception: %s" % (
  285. last_exception.__class__.__name__, last_exception))
  286. raise last_exception
  287. self[key] = val
  288. elif key in self._dicts:
  289. self[key] = LazyLoadMetadata(self._url + key + '/',
  290. self._num_retries)
  291. return super(LazyLoadMetadata, self).__getitem__(key)
  292. def get(self, key, default=None):
  293. try:
  294. return self[key]
  295. except KeyError:
  296. return default
  297. def values(self):
  298. self._materialize()
  299. return super(LazyLoadMetadata, self).values()
  300. def items(self):
  301. self._materialize()
  302. return super(LazyLoadMetadata, self).items()
  303. def __str__(self):
  304. self._materialize()
  305. return super(LazyLoadMetadata, self).__str__()
  306. def __repr__(self):
  307. self._materialize()
  308. return super(LazyLoadMetadata, self).__repr__()
  309. def _build_instance_metadata_url(url, version, path):
  310. """
  311. Builds an EC2 metadata URL for fetching information about an instance.
  312. Example:
  313. >>> _build_instance_metadata_url('http://169.254.169.254', 'latest', 'meta-data/')
  314. http://169.254.169.254/latest/meta-data/
  315. :type url: string
  316. :param url: URL to metadata service, e.g. 'http://169.254.169.254'
  317. :type version: string
  318. :param version: Version of the metadata to get, e.g. 'latest'
  319. :type path: string
  320. :param path: Path of the metadata to get, e.g. 'meta-data/'. If a trailing
  321. slash is required it must be passed in with the path.
  322. :return: The full metadata URL
  323. """
  324. return '%s/%s/%s' % (url, version, path)
  325. def get_instance_metadata(version='latest', url='http://169.254.169.254',
  326. data='meta-data/', timeout=None, num_retries=5):
  327. """
  328. Returns the instance metadata as a nested Python dictionary.
  329. Simple values (e.g. local_hostname, hostname, etc.) will be
  330. stored as string values. Values such as ancestor-ami-ids will
  331. be stored in the dict as a list of string values. More complex
  332. fields such as public-keys and will be stored as nested dicts.
  333. If the timeout is specified, the connection to the specified url
  334. will time out after the specified number of seconds.
  335. """
  336. try:
  337. metadata_url = _build_instance_metadata_url(url, version, data)
  338. return _get_instance_metadata(metadata_url, num_retries=num_retries, timeout=timeout)
  339. except urllib.error.URLError:
  340. boto.log.exception("Exception caught when trying to retrieve "
  341. "instance metadata for: %s", data)
  342. return None
  343. def get_instance_identity(version='latest', url='http://169.254.169.254',
  344. timeout=None, num_retries=5):
  345. """
  346. Returns the instance identity as a nested Python dictionary.
  347. """
  348. iid = {}
  349. base_url = _build_instance_metadata_url(url, version,
  350. 'dynamic/instance-identity/')
  351. try:
  352. data = retry_url(base_url, num_retries=num_retries, timeout=timeout)
  353. fields = data.split('\n')
  354. for field in fields:
  355. val = retry_url(base_url + '/' + field + '/', num_retries=num_retries, timeout=timeout)
  356. if val[0] == '{':
  357. val = json.loads(val)
  358. if field:
  359. iid[field] = val
  360. return iid
  361. except urllib.error.URLError:
  362. return None
  363. def get_instance_userdata(version='latest', sep=None,
  364. url='http://169.254.169.254', timeout=None, num_retries=5):
  365. ud_url = _build_instance_metadata_url(url, version, 'user-data')
  366. user_data = retry_url(ud_url, retry_on_404=False, num_retries=num_retries, timeout=timeout)
  367. if user_data:
  368. if sep:
  369. l = user_data.split(sep)
  370. user_data = {}
  371. for nvpair in l:
  372. t = nvpair.split('=')
  373. user_data[t[0].strip()] = t[1].strip()
  374. return user_data
  375. ISO8601 = '%Y-%m-%dT%H:%M:%SZ'
  376. ISO8601_MS = '%Y-%m-%dT%H:%M:%S.%fZ'
  377. RFC1123 = '%a, %d %b %Y %H:%M:%S %Z'
  378. LOCALE_LOCK = threading.Lock()
  379. @contextmanager
  380. def setlocale(name):
  381. """
  382. A context manager to set the locale in a threadsafe manner.
  383. """
  384. with LOCALE_LOCK:
  385. saved = locale.setlocale(locale.LC_ALL)
  386. try:
  387. yield locale.setlocale(locale.LC_ALL, name)
  388. finally:
  389. locale.setlocale(locale.LC_ALL, saved)
  390. def get_ts(ts=None):
  391. if not ts:
  392. ts = time.gmtime()
  393. return time.strftime(ISO8601, ts)
  394. def parse_ts(ts):
  395. with setlocale('C'):
  396. ts = ts.strip()
  397. try:
  398. dt = datetime.datetime.strptime(ts, ISO8601)
  399. return dt
  400. except ValueError:
  401. try:
  402. dt = datetime.datetime.strptime(ts, ISO8601_MS)
  403. return dt
  404. except ValueError:
  405. dt = datetime.datetime.strptime(ts, RFC1123)
  406. return dt
  407. def find_class(module_name, class_name=None):
  408. if class_name:
  409. module_name = "%s.%s" % (module_name, class_name)
  410. modules = module_name.split('.')
  411. c = None
  412. try:
  413. for m in modules[1:]:
  414. if c:
  415. c = getattr(c, m)
  416. else:
  417. c = getattr(__import__(".".join(modules[0:-1])), m)
  418. return c
  419. except:
  420. return None
  421. def update_dme(username, password, dme_id, ip_address):
  422. """
  423. Update your Dynamic DNS record with DNSMadeEasy.com
  424. """
  425. dme_url = 'https://www.dnsmadeeasy.com/servlet/updateip'
  426. dme_url += '?username=%s&password=%s&id=%s&ip=%s'
  427. s = urllib.request.urlopen(dme_url % (username, password, dme_id, ip_address))
  428. return s.read()
  429. def fetch_file(uri, file=None, username=None, password=None):
  430. """
  431. Fetch a file based on the URI provided.
  432. If you do not pass in a file pointer a tempfile.NamedTemporaryFile,
  433. or None if the file could not be retrieved is returned.
  434. The URI can be either an HTTP url, or "s3://bucket_name/key_name"
  435. """
  436. boto.log.info('Fetching %s' % uri)
  437. if file is None:
  438. file = tempfile.NamedTemporaryFile()
  439. try:
  440. if uri.startswith('s3://'):
  441. bucket_name, key_name = uri[len('s3://'):].split('/', 1)
  442. c = boto.connect_s3(aws_access_key_id=username,
  443. aws_secret_access_key=password)
  444. bucket = c.get_bucket(bucket_name)
  445. key = bucket.get_key(key_name)
  446. key.get_contents_to_file(file)
  447. else:
  448. if username and password:
  449. passman = urllib.request.HTTPPasswordMgrWithDefaultRealm()
  450. passman.add_password(None, uri, username, password)
  451. authhandler = urllib.request.HTTPBasicAuthHandler(passman)
  452. opener = urllib.request.build_opener(authhandler)
  453. urllib.request.install_opener(opener)
  454. s = urllib.request.urlopen(uri)
  455. file.write(s.read())
  456. file.seek(0)
  457. except:
  458. raise
  459. boto.log.exception('Problem Retrieving file: %s' % uri)
  460. file = None
  461. return file
  462. class ShellCommand(object):
  463. def __init__(self, command, wait=True, fail_fast=False, cwd=None):
  464. self.exit_code = 0
  465. self.command = command
  466. self.log_fp = StringIO()
  467. self.wait = wait
  468. self.fail_fast = fail_fast
  469. self.run(cwd=cwd)
  470. def run(self, cwd=None):
  471. boto.log.info('running:%s' % self.command)
  472. self.process = subprocess.Popen(self.command, shell=True,
  473. stdin=subprocess.PIPE,
  474. stdout=subprocess.PIPE,
  475. stderr=subprocess.PIPE,
  476. cwd=cwd)
  477. if(self.wait):
  478. while self.process.poll() is None:
  479. time.sleep(1)
  480. t = self.process.communicate()
  481. self.log_fp.write(t[0])
  482. self.log_fp.write(t[1])
  483. boto.log.info(self.log_fp.getvalue())
  484. self.exit_code = self.process.returncode
  485. if self.fail_fast and self.exit_code != 0:
  486. raise Exception("Command " + self.command +
  487. " failed with status " + self.exit_code)
  488. return self.exit_code
  489. def setReadOnly(self, value):
  490. raise AttributeError
  491. def getStatus(self):
  492. return self.exit_code
  493. status = property(getStatus, setReadOnly, None,
  494. 'The exit code for the command')
  495. def getOutput(self):
  496. return self.log_fp.getvalue()
  497. output = property(getOutput, setReadOnly, None,
  498. 'The STDIN and STDERR output of the command')
  499. class AuthSMTPHandler(logging.handlers.SMTPHandler):
  500. """
  501. This class extends the SMTPHandler in the standard Python logging module
  502. to accept a username and password on the constructor and to then use those
  503. credentials to authenticate with the SMTP server. To use this, you could
  504. add something like this in your boto config file:
  505. [handler_hand07]
  506. class=boto.utils.AuthSMTPHandler
  507. level=WARN
  508. formatter=form07
  509. args=('localhost', 'username', 'password', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')
  510. """
  511. def __init__(self, mailhost, username, password,
  512. fromaddr, toaddrs, subject):
  513. """
  514. Initialize the handler.
  515. We have extended the constructor to accept a username/password
  516. for SMTP authentication.
  517. """
  518. super(AuthSMTPHandler, self).__init__(mailhost, fromaddr,
  519. toaddrs, subject)
  520. self.username = username
  521. self.password = password
  522. def emit(self, record):
  523. """
  524. Emit a record.
  525. Format the record and send it to the specified addressees.
  526. It would be really nice if I could add authorization to this class
  527. without having to resort to cut and paste inheritance but, no.
  528. """
  529. try:
  530. port = self.mailport
  531. if not port:
  532. port = smtplib.SMTP_PORT
  533. smtp = smtplib.SMTP(self.mailhost, port)
  534. smtp.login(self.username, self.password)
  535. msg = self.format(record)
  536. msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % (
  537. self.fromaddr,
  538. ','.join(self.toaddrs),
  539. self.getSubject(record),
  540. email.utils.formatdate(), msg)
  541. smtp.sendmail(self.fromaddr, self.toaddrs, msg)
  542. smtp.quit()
  543. except (KeyboardInterrupt, SystemExit):
  544. raise
  545. except:
  546. self.handleError(record)
  547. class LRUCache(dict):
  548. """A dictionary-like object that stores only a certain number of items, and
  549. discards its least recently used item when full.
  550. >>> cache = LRUCache(3)
  551. >>> cache['A'] = 0
  552. >>> cache['B'] = 1
  553. >>> cache['C'] = 2
  554. >>> len(cache)
  555. 3
  556. >>> cache['A']
  557. 0
  558. Adding new items to the cache does not increase its size. Instead, the least
  559. recently used item is dropped:
  560. >>> cache['D'] = 3
  561. >>> len(cache)
  562. 3
  563. >>> 'B' in cache
  564. False
  565. Iterating over the cache returns the keys, starting with the most recently
  566. used:
  567. >>> for key in cache:
  568. ... print key
  569. D
  570. A
  571. C
  572. This code is based on the LRUCache class from Genshi which is based on
  573. `Myghty <http://www.myghty.org>`_'s LRUCache from ``myghtyutils.util``,
  574. written by Mike Bayer and released under the MIT license (Genshi uses the
  575. BSD License).
  576. """
  577. class _Item(object):
  578. def __init__(self, key, value):
  579. self.previous = self.next = None
  580. self.key = key
  581. self.value = value
  582. def __repr__(self):
  583. return repr(self.value)
  584. def __init__(self, capacity):
  585. self._dict = dict()
  586. self.capacity = capacity
  587. self.head = None
  588. self.tail = None
  589. def __contains__(self, key):
  590. return key in self._dict
  591. def __iter__(self):
  592. cur = self.head
  593. while cur:
  594. yield cur.key
  595. cur = cur.next
  596. def __len__(self):
  597. return len(self._dict)
  598. def __getitem__(self, key):
  599. item = self._dict[key]
  600. self._update_item(item)
  601. return item.value
  602. def __setitem__(self, key, value):
  603. item = self._dict.get(key)
  604. if item is None:
  605. item = self._Item(key, value)
  606. self._dict[key] = item
  607. self._insert_item(item)
  608. else:
  609. item.value = value
  610. self._update_item(item)
  611. self._manage_size()
  612. def __repr__(self):
  613. return repr(self._dict)
  614. def _insert_item(self, item):
  615. item.previous = None
  616. item.next = self.head
  617. if self.head is not None:
  618. self.head.previous = item
  619. else:
  620. self.tail = item
  621. self.head = item
  622. self._manage_size()
  623. def _manage_size(self):
  624. while len(self._dict) > self.capacity:
  625. del self._dict[self.tail.key]
  626. if self.tail != self.head:
  627. self.tail = self.tail.previous
  628. self.tail.next = None
  629. else:
  630. self.head = self.tail = None
  631. def _update_item(self, item):
  632. if self.head == item:
  633. return
  634. previous = item.previous
  635. previous.next = item.next
  636. if item.next is not None:
  637. item.next.previous = previous
  638. else:
  639. self.tail = previous
  640. item.previous = None
  641. item.next = self.head
  642. self.head.previous = self.head = item
  643. class Password(object):
  644. """
  645. Password object that stores itself as hashed.
  646. Hash defaults to SHA512 if available, MD5 otherwise.
  647. """
  648. hashfunc = _hashfn
  649. def __init__(self, str=None, hashfunc=None):
  650. """
  651. Load the string from an initial value, this should be the
  652. raw hashed password.
  653. """
  654. self.str = str
  655. if hashfunc:
  656. self.hashfunc = hashfunc
  657. def set(self, value):
  658. if not isinstance(value, bytes):
  659. value = value.encode('utf-8')
  660. self.str = self.hashfunc(value).hexdigest()
  661. def __str__(self):
  662. return str(self.str)
  663. def __eq__(self, other):
  664. if other is None:
  665. return False
  666. if not isinstance(other, bytes):
  667. other = other.encode('utf-8')
  668. return str(self.hashfunc(other).hexdigest()) == str(self.str)
  669. def __len__(self):
  670. if self.str:
  671. return len(self.str)
  672. else:
  673. return 0
  674. def notify(subject, body=None, html_body=None, to_string=None,
  675. attachments=None, append_instance_id=True):
  676. attachments = attachments or []
  677. if append_instance_id:
  678. subject = "[%s] %s" % (
  679. boto.config.get_value("Instance", "instance-id"), subject)
  680. if not to_string:
  681. to_string = boto.config.get_value('Notification', 'smtp_to', None)
  682. if to_string:
  683. try:
  684. from_string = boto.config.get_value('Notification',
  685. 'smtp_from', 'boto')
  686. msg = email.mime.multipart.MIMEMultipart()
  687. msg['From'] = from_string
  688. msg['Reply-To'] = from_string
  689. msg['To'] = to_string
  690. msg['Date'] = email.utils.formatdate(localtime=True)
  691. msg['Subject'] = subject
  692. if body:
  693. msg.attach(email.mime.text.MIMEText(body))
  694. if html_body:
  695. part = email.mime.base.MIMEBase('text', 'html')
  696. part.set_payload(html_body)
  697. email.encoders.encode_base64(part)
  698. msg.attach(part)
  699. for part in attachments:
  700. msg.attach(part)
  701. smtp_host = boto.config.get_value('Notification',
  702. 'smtp_host', 'localhost')
  703. # Alternate port support
  704. if boto.config.get_value("Notification", "smtp_port"):
  705. server = smtplib.SMTP(smtp_host, int(
  706. boto.config.get_value("Notification", "smtp_port")))
  707. else:
  708. server = smtplib.SMTP(smtp_host)
  709. # TLS support
  710. if boto.config.getbool("Notification", "smtp_tls"):
  711. server.ehlo()
  712. server.starttls()
  713. server.ehlo()
  714. smtp_user = boto.config.get_value('Notification', 'smtp_user', '')
  715. smtp_pass = boto.config.get_value('Notification', 'smtp_pass', '')
  716. if smtp_user:
  717. server.login(smtp_user, smtp_pass)
  718. server.sendmail(from_string, to_string, msg.as_string())
  719. server.quit()
  720. except:
  721. boto.log.exception('notify failed')
  722. def get_utf8_value(value):
  723. if not six.PY2 and isinstance(value, bytes):
  724. return value
  725. if not isinstance(value, six.string_types):
  726. value = six.text_type(value)
  727. if isinstance(value, six.text_type):
  728. value = value.encode('utf-8')
  729. return value
  730. def mklist(value):
  731. if not isinstance(value, list):
  732. if isinstance(value, tuple):
  733. value = list(value)
  734. else:
  735. value = [value]
  736. return value
  737. def pythonize_name(name):
  738. """Convert camel case to a "pythonic" name.
  739. Examples::
  740. pythonize_name('CamelCase') -> 'camel_case'
  741. pythonize_name('already_pythonized') -> 'already_pythonized'
  742. pythonize_name('HTTPRequest') -> 'http_request'
  743. pythonize_name('HTTPStatus200Ok') -> 'http_status_200_ok'
  744. pythonize_name('UPPER') -> 'upper'
  745. pythonize_name('') -> ''
  746. """
  747. s1 = _first_cap_regex.sub(r'\1_\2', name)
  748. s2 = _number_cap_regex.sub(r'\1_\2', s1)
  749. return _end_cap_regex.sub(r'\1_\2', s2).lower()
  750. def write_mime_multipart(content, compress=False, deftype='text/plain', delimiter=':'):
  751. """Description:
  752. :param content: A list of tuples of name-content pairs. This is used
  753. instead of a dict to ensure that scripts run in order
  754. :type list of tuples:
  755. :param compress: Use gzip to compress the scripts, defaults to no compression
  756. :type bool:
  757. :param deftype: The type that should be assumed if nothing else can be figured out
  758. :type str:
  759. :param delimiter: mime delimiter
  760. :type str:
  761. :return: Final mime multipart
  762. :rtype: str:
  763. """
  764. wrapper = email.mime.multipart.MIMEMultipart()
  765. for name, con in content:
  766. definite_type = guess_mime_type(con, deftype)
  767. maintype, subtype = definite_type.split('/', 1)
  768. if maintype == 'text':
  769. mime_con = email.mime.text.MIMEText(con, _subtype=subtype)
  770. else:
  771. mime_con = email.mime.base.MIMEBase(maintype, subtype)
  772. mime_con.set_payload(con)
  773. # Encode the payload using Base64
  774. email.encoders.encode_base64(mime_con)
  775. mime_con.add_header('Content-Disposition', 'attachment', filename=name)
  776. wrapper.attach(mime_con)
  777. rcontent = wrapper.as_string()
  778. if compress:
  779. buf = StringIO()
  780. gz = gzip.GzipFile(mode='wb', fileobj=buf)
  781. try:
  782. gz.write(rcontent)
  783. finally:
  784. gz.close()
  785. rcontent = buf.getvalue()
  786. return rcontent
  787. def guess_mime_type(content, deftype):
  788. """Description: Guess the mime type of a block of text
  789. :param content: content we're finding the type of
  790. :type str:
  791. :param deftype: Default mime type
  792. :type str:
  793. :rtype: <type>:
  794. :return: <description>
  795. """
  796. # Mappings recognized by cloudinit
  797. starts_with_mappings = {
  798. '#include': 'text/x-include-url',
  799. '#!': 'text/x-shellscript',
  800. '#cloud-config': 'text/cloud-config',
  801. '#upstart-job': 'text/upstart-job',
  802. '#part-handler': 'text/part-handler',
  803. '#cloud-boothook': 'text/cloud-boothook'
  804. }
  805. rtype = deftype
  806. for possible_type, mimetype in starts_with_mappings.items():
  807. if content.startswith(possible_type):
  808. rtype = mimetype
  809. break
  810. return(rtype)
  811. def compute_md5(fp, buf_size=8192, size=None):
  812. """
  813. Compute MD5 hash on passed file and return results in a tuple of values.
  814. :type fp: file
  815. :param fp: File pointer to the file to MD5 hash. The file pointer
  816. will be reset to its current location before the
  817. method returns.
  818. :type buf_size: integer
  819. :param buf_size: Number of bytes per read request.
  820. :type size: int
  821. :param size: (optional) The Maximum number of bytes to read from
  822. the file pointer (fp). This is useful when uploading
  823. a file in multiple parts where the file is being
  824. split inplace into different parts. Less bytes may
  825. be available.
  826. :rtype: tuple
  827. :return: A tuple containing the hex digest version of the MD5 hash
  828. as the first element, the base64 encoded version of the
  829. plain digest as the second element and the data size as
  830. the third element.
  831. """
  832. return compute_hash(fp, buf_size, size, hash_algorithm=md5)
  833. def compute_hash(fp, buf_size=8192, size=None, hash_algorithm=md5):
  834. hash_obj = hash_algorithm()
  835. spos = fp.tell()
  836. if size and size < buf_size:
  837. s = fp.read(size)
  838. else:
  839. s = fp.read(buf_size)
  840. while s:
  841. if not isinstance(s, bytes):
  842. s = s.encode('utf-8')
  843. hash_obj.update(s)
  844. if size:
  845. size -= len(s)
  846. if size <= 0:
  847. break
  848. if size and size < buf_size:
  849. s = fp.read(size)
  850. else:
  851. s = fp.read(buf_size)
  852. hex_digest = hash_obj.hexdigest()
  853. base64_digest = encodebytes(hash_obj.digest()).decode('utf-8')
  854. if base64_digest[-1] == '\n':
  855. base64_digest = base64_digest[0:-1]
  856. # data_size based on bytes read.
  857. data_size = fp.tell() - spos
  858. fp.seek(spos)
  859. return (hex_digest, base64_digest, data_size)
  860. def find_matching_headers(name, headers):
  861. """
  862. Takes a specific header name and a dict of headers {"name": "value"}.
  863. Returns a list of matching header names, case-insensitive.
  864. """
  865. return [h for h in headers if h.lower() == name.lower()]
  866. def merge_headers_by_name(name, headers):
  867. """
  868. Takes a specific header name and a dict of headers {"name": "value"}.
  869. Returns a string of all header values, comma-separated, that match the
  870. input header name, case-insensitive.
  871. """
  872. matching_headers = find_matching_headers(name, headers)
  873. return ','.join(str(headers[h]) for h in matching_headers
  874. if headers[h] is not None)
  875. class RequestHook(object):
  876. """
  877. This can be extended and supplied to the connection object
  878. to gain access to request and response object after the request completes.
  879. One use for this would be to implement some specific request logging.
  880. """
  881. def handle_request_data(self, request, response, error=False):
  882. pass
  883. def host_is_ipv6(hostname):
  884. """
  885. Detect (naively) if the hostname is an IPV6 host.
  886. Return a boolean.
  887. """
  888. # empty strings or anything that is not a string is automatically not an
  889. # IPV6 address
  890. if not hostname or not isinstance(hostname, str):
  891. return False
  892. if hostname.startswith('['):
  893. return True
  894. if len(hostname.split(':')) > 2:
  895. return True
  896. # Anything else that doesn't start with brackets or doesn't have more than
  897. # one ':' should not be an IPV6 address. This is very naive but the rest of
  898. # the connection chain should error accordingly for typos or ill formed
  899. # addresses
  900. return False
  901. def parse_host(hostname):
  902. """
  903. Given a hostname that may have a port name, ensure that the port is trimmed
  904. returning only the host, including hostnames that are IPV6 and may include
  905. brackets.
  906. """
  907. # ensure that hostname does not have any whitespaces
  908. hostname = hostname.strip()
  909. if host_is_ipv6(hostname):
  910. return hostname.split(']:', 1)[0].strip('[]')
  911. else:
  912. return hostname.split(':', 1)[0]