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