utils.py 34 KB

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