utils.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. # Copyright 2013 dotCloud inc.
  2. # Licensed under the Apache License, Version 2.0 (the "License");
  3. # you may not use this file except in compliance with the License.
  4. # You may obtain a copy of the License at
  5. # http://www.apache.org/licenses/LICENSE-2.0
  6. # Unless required by applicable law or agreed to in writing, software
  7. # distributed under the License is distributed on an "AS IS" BASIS,
  8. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. # See the License for the specific language governing permissions and
  10. # limitations under the License.
  11. import io
  12. import tarfile
  13. import tempfile
  14. import requests
  15. from fig.packages import six
  16. def mkbuildcontext(dockerfile):
  17. f = tempfile.NamedTemporaryFile()
  18. t = tarfile.open(mode='w', fileobj=f)
  19. if isinstance(dockerfile, io.StringIO):
  20. dfinfo = tarfile.TarInfo('Dockerfile')
  21. if six.PY3:
  22. raise TypeError('Please use io.BytesIO to create in-memory '
  23. 'Dockerfiles with Python 3')
  24. else:
  25. dfinfo.size = len(dockerfile.getvalue())
  26. elif isinstance(dockerfile, io.BytesIO):
  27. dfinfo = tarfile.TarInfo('Dockerfile')
  28. dfinfo.size = len(dockerfile.getvalue())
  29. else:
  30. dfinfo = t.gettarinfo(fileobj=dockerfile, arcname='Dockerfile')
  31. t.addfile(dfinfo, dockerfile)
  32. t.close()
  33. f.seek(0)
  34. return f
  35. def tar(path):
  36. f = tempfile.NamedTemporaryFile()
  37. t = tarfile.open(mode='w', fileobj=f)
  38. t.add(path, arcname='.')
  39. t.close()
  40. f.seek(0)
  41. return f
  42. def compare_version(v1, v2):
  43. return float(v2) - float(v1)
  44. def ping(url):
  45. try:
  46. res = requests.get(url)
  47. return res.status >= 400
  48. except Exception:
  49. return False
  50. def _convert_port_binding(binding):
  51. result = {'HostIp': '', 'HostPort': ''}
  52. if isinstance(binding, tuple):
  53. if len(binding) == 2:
  54. result['HostPort'] = binding[1]
  55. result['HostIp'] = binding[0]
  56. elif isinstance(binding[0], six.string_types):
  57. result['HostIp'] = binding[0]
  58. else:
  59. result['HostPort'] = binding[0]
  60. else:
  61. result['HostPort'] = binding
  62. if result['HostPort'] is None:
  63. result['HostPort'] = ''
  64. else:
  65. result['HostPort'] = str(result['HostPort'])
  66. return result
  67. def convert_port_bindings(port_bindings):
  68. result = {}
  69. for k, v in six.iteritems(port_bindings):
  70. key = str(k)
  71. if '/' not in key:
  72. key = key + '/tcp'
  73. if isinstance(v, list):
  74. result[key] = [_convert_port_binding(binding) for binding in v]
  75. else:
  76. result[key] = [_convert_port_binding(v)]
  77. return result