upload.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. #!/usr/bin/python
  2. #
  3. # This Source Code Form is subject to the terms of the Mozilla Public
  4. # License, v. 2.0. If a copy of the MPL was not distributed with this
  5. # file, You can obtain one at http://mozilla.org/MPL/2.0/.
  6. #
  7. # When run directly, this script expects the following environment variables
  8. # to be set:
  9. # UPLOAD_HOST : host to upload files to
  10. # UPLOAD_USER : username on that host
  11. # and one of the following:
  12. # UPLOAD_PATH : path on that host to put the files in
  13. # UPLOAD_TO_TEMP : upload files to a new temporary directory
  14. #
  15. # If UPLOAD_HOST and UPLOAD_USER are not set, this script will simply write out
  16. # the properties file.
  17. #
  18. # If UPLOAD_HOST is "localhost", then files are simply copied to UPLOAD_PATH.
  19. # In this case, UPLOAD_TO_TEMP and POST_UPLOAD_CMD are not supported, and no
  20. # properties are written out.
  21. #
  22. # And will use the following optional environment variables if set:
  23. # UPLOAD_SSH_KEY : path to a ssh private key to use
  24. # UPLOAD_PORT : port to use for ssh
  25. # POST_UPLOAD_CMD: a commandline to run on the remote host after uploading.
  26. # UPLOAD_PATH and the full paths of all files uploaded will
  27. # be appended to the commandline.
  28. #
  29. # All files to be uploaded should be passed as commandline arguments to this
  30. # script. The script takes one other parameter, --base-path, which you can use
  31. # to indicate that files should be uploaded including their paths relative
  32. # to the base path.
  33. import sys, os
  34. import re
  35. import json
  36. import errno
  37. import hashlib
  38. import shutil
  39. from optparse import OptionParser
  40. from subprocess import (
  41. check_call,
  42. check_output,
  43. STDOUT,
  44. CalledProcessError,
  45. )
  46. import concurrent.futures as futures
  47. import redo
  48. def OptionalEnvironmentVariable(v):
  49. """Return the value of the environment variable named v, or None
  50. if it's unset (or empty)."""
  51. if v in os.environ and os.environ[v] != "":
  52. return os.environ[v]
  53. return None
  54. def FixupMsysPath(path):
  55. """MSYS helpfully translates absolute pathnames in environment variables
  56. and commandline arguments into Windows native paths. This sucks if you're
  57. trying to pass an absolute path on a remote server. This function attempts
  58. to un-mangle such paths."""
  59. if 'OSTYPE' in os.environ and os.environ['OSTYPE'] == 'msys':
  60. # sort of awful, find out where our shell is (should be in msys/bin)
  61. # and strip the first part of that path out of the other path
  62. if 'SHELL' in os.environ:
  63. sh = os.environ['SHELL']
  64. msys = sh[:sh.find('/bin')]
  65. if path.startswith(msys):
  66. path = path[len(msys):]
  67. return path
  68. def WindowsPathToMsysPath(path):
  69. """Translate a Windows pathname to an MSYS pathname.
  70. Necessary because we call out to ssh/scp, which are MSYS binaries
  71. and expect MSYS paths."""
  72. # If we're not on Windows, or if we already have an MSYS path (starting
  73. # with '/' instead of 'c:' or something), then just return.
  74. if sys.platform != 'win32' or path.startswith('/'):
  75. return path
  76. (drive, path) = os.path.splitdrive(os.path.abspath(path))
  77. return "/" + drive[0] + path.replace('\\','/')
  78. def AppendOptionalArgsToSSHCommandline(cmdline, port, ssh_key):
  79. """Given optional port and ssh key values, append valid OpenSSH
  80. commandline arguments to the list cmdline if the values are not None."""
  81. if port is not None:
  82. cmdline.append("-P%d" % port)
  83. if ssh_key is not None:
  84. # Don't interpret ~ paths - ssh can handle that on its own
  85. if not ssh_key.startswith('~'):
  86. ssh_key = WindowsPathToMsysPath(ssh_key)
  87. cmdline.extend(["-o", "IdentityFile=%s" % ssh_key])
  88. # In case of an issue here we don't want to hang on a password prompt.
  89. cmdline.extend(["-o", "BatchMode=yes"])
  90. def DoSSHCommand(command, user, host, port=None, ssh_key=None):
  91. """Execute command on user@host using ssh. Optionally use
  92. port and ssh_key, if provided."""
  93. cmdline = ["ssh"]
  94. AppendOptionalArgsToSSHCommandline(cmdline, port, ssh_key)
  95. cmdline.extend(["%s@%s" % (user, host), command])
  96. with redo.retrying(check_output, sleeptime=10) as f:
  97. try:
  98. output = f(cmdline, stderr=STDOUT).strip()
  99. except CalledProcessError as e:
  100. print "failed ssh command output:"
  101. print '=' * 20
  102. print e.output
  103. print '=' * 20
  104. raise
  105. return output
  106. raise Exception("Command %s returned non-zero exit code" % cmdline)
  107. def DoSCPFile(file, remote_path, user, host, port=None, ssh_key=None,
  108. log=False):
  109. """Upload file to user@host:remote_path using scp. Optionally use
  110. port and ssh_key, if provided."""
  111. if log:
  112. print 'Uploading %s' % file
  113. cmdline = ["scp"]
  114. AppendOptionalArgsToSSHCommandline(cmdline, port, ssh_key)
  115. cmdline.extend([WindowsPathToMsysPath(file),
  116. "%s@%s:%s" % (user, host, remote_path)])
  117. with redo.retrying(check_call, sleeptime=10) as f:
  118. f(cmdline)
  119. return
  120. raise Exception("Command %s returned non-zero exit code" % cmdline)
  121. def GetBaseRelativePath(path, local_file, base_path):
  122. """Given a remote path to upload to, a full path to a local file, and an
  123. optional full path that is a base path of the local file, construct the
  124. full remote path to place the file in. If base_path is not None, include
  125. the relative path from base_path to file."""
  126. if base_path is None or not local_file.startswith(base_path):
  127. # Hack to work around OSX uploading the i386 SDK from i386/dist. Both
  128. # the i386 SDK and x86-64 SDK end up in the same directory this way.
  129. if base_path.endswith('/x86_64/dist'):
  130. return GetBaseRelativePath(path, local_file, base_path.replace('/x86_64/', '/i386/'))
  131. return path
  132. dir = os.path.dirname(local_file)
  133. # strip base_path + extra slash and make it unixy
  134. dir = dir[len(base_path)+1:].replace('\\','/')
  135. return path + dir
  136. def GetFileHashAndSize(filename):
  137. sha512Hash = 'UNKNOWN'
  138. size = 'UNKNOWN'
  139. try:
  140. # open in binary mode to make sure we get consistent results
  141. # across all platforms
  142. with open(filename, "rb") as f:
  143. shaObj = hashlib.sha512(f.read())
  144. sha512Hash = shaObj.hexdigest()
  145. size = os.path.getsize(filename)
  146. except:
  147. raise Exception("Unable to get filesize/hash from file: %s" % filename)
  148. return (sha512Hash, size)
  149. def GetMarProperties(filename):
  150. if not os.path.exists(filename):
  151. return {}
  152. (mar_hash, mar_size) = GetFileHashAndSize(filename)
  153. return {
  154. 'completeMarFilename': os.path.basename(filename),
  155. 'completeMarSize': mar_size,
  156. 'completeMarHash': mar_hash,
  157. }
  158. def GetUrlProperties(output, package):
  159. # let's create a switch case using name-spaces/dict
  160. # rather than a long if/else with duplicate code
  161. property_conditions = [
  162. # key: property name, value: condition
  163. ('symbolsUrl', lambda m: m.endswith('crashreporter-symbols.zip') or
  164. m.endswith('crashreporter-symbols-full.zip')),
  165. ('testsUrl', lambda m: m.endswith(('tests.tar.bz2', 'tests.zip'))),
  166. ('robocopApkUrl', lambda m: m.endswith('apk') and 'robocop' in m),
  167. ('jsshellUrl', lambda m: 'jsshell-' in m and m.endswith('.zip')),
  168. ('completeMarUrl', lambda m: m.endswith('.complete.mar')),
  169. ('partialMarUrl', lambda m: m.endswith('.mar') and '.partial.' in m),
  170. ('codeCoverageURL', lambda m: m.endswith('code-coverage-gcno.zip')),
  171. ('sdkUrl', lambda m: m.endswith(('sdk.tar.bz2', 'sdk.zip'))),
  172. ('testPackagesUrl', lambda m: m.endswith('test_packages.json')),
  173. ('packageUrl', lambda m: m.endswith(package)),
  174. ]
  175. url_re = re.compile(r'''^(https?://.*?\.(?:tar\.bz2|dmg|zip|apk|rpm|mar|tar\.gz|json))$''')
  176. properties = {}
  177. try:
  178. for line in output.splitlines():
  179. m = url_re.match(line.strip())
  180. if m:
  181. m = m.group(1)
  182. for prop, condition in property_conditions:
  183. if condition(m):
  184. properties.update({prop: m})
  185. break
  186. except IOError as e:
  187. if e.errno != errno.ENOENT:
  188. raise
  189. properties = {prop: 'UNKNOWN' for prop, condition in property_conditions}
  190. return properties
  191. def UploadFiles(user, host, path, files, verbose=False, port=None, ssh_key=None, base_path=None, upload_to_temp_dir=False, post_upload_command=None, package=None):
  192. """Upload each file in the list files to user@host:path. Optionally pass
  193. port and ssh_key to the ssh commands. If base_path is not None, upload
  194. files including their path relative to base_path. If upload_to_temp_dir is
  195. True files will be uploaded to a temporary directory on the remote server.
  196. Generally, you should have a post upload command specified in these cases
  197. that can move them around to their correct location(s).
  198. If post_upload_command is not None, execute that command on the remote host
  199. after uploading all files, passing it the upload path, and the full paths to
  200. all files uploaded.
  201. If verbose is True, print status updates while working."""
  202. if not host or not user:
  203. return {}
  204. if (not path and not upload_to_temp_dir) or (path and upload_to_temp_dir):
  205. print "One (and only one of UPLOAD_PATH or UPLOAD_TO_TEMP must be " + \
  206. "defined."
  207. sys.exit(1)
  208. if upload_to_temp_dir:
  209. path = DoSSHCommand("mktemp -d", user, host, port=port, ssh_key=ssh_key)
  210. if not path.endswith("/"):
  211. path += "/"
  212. if base_path is not None:
  213. base_path = os.path.abspath(base_path)
  214. remote_files = []
  215. properties = {}
  216. def get_remote_path(p):
  217. return GetBaseRelativePath(path, os.path.abspath(p), base_path)
  218. try:
  219. # Do a pass to find remote directories so we don't perform excessive
  220. # scp calls.
  221. remote_paths = set()
  222. for file in files:
  223. if not os.path.isfile(file):
  224. raise IOError("File not found: %s" % file)
  225. remote_paths.add(get_remote_path(file))
  226. # If we wanted to, we could reduce the remote paths if they are a parent
  227. # of any entry.
  228. for p in sorted(remote_paths):
  229. DoSSHCommand("mkdir -p " + p, user, host, port=port, ssh_key=ssh_key)
  230. with futures.ThreadPoolExecutor(4) as e:
  231. fs = []
  232. # Since we're uploading in parallel, the largest file should take
  233. # the longest to upload. So start it first.
  234. for file in sorted(files, key=os.path.getsize, reverse=True):
  235. remote_path = get_remote_path(file)
  236. fs.append(e.submit(DoSCPFile, file, remote_path, user, host,
  237. port=port, ssh_key=ssh_key, log=verbose))
  238. remote_files.append(remote_path + '/' + os.path.basename(file))
  239. # We need to call result() on the future otherwise exceptions could
  240. # get swallowed.
  241. for f in futures.as_completed(fs):
  242. f.result()
  243. if post_upload_command is not None:
  244. if verbose:
  245. print "Running post-upload command: " + post_upload_command
  246. file_list = '"' + '" "'.join(remote_files) + '"'
  247. output = DoSSHCommand('%s "%s" %s' % (post_upload_command, path, file_list), user, host, port=port, ssh_key=ssh_key)
  248. # We print since mozharness may parse URLs from the output stream.
  249. print output
  250. properties = GetUrlProperties(output, package)
  251. finally:
  252. if upload_to_temp_dir:
  253. DoSSHCommand("rm -rf %s" % path, user, host, port=port,
  254. ssh_key=ssh_key)
  255. if verbose:
  256. print "Upload complete"
  257. return properties
  258. def CopyFilesLocally(path, files, verbose=False, base_path=None, package=None):
  259. """Copy each file in the list of files to `path`. The `base_path` argument is treated
  260. as it is by UploadFiles."""
  261. if not path.endswith("/"):
  262. path += "/"
  263. if base_path is not None:
  264. base_path = os.path.abspath(base_path)
  265. for file in files:
  266. file = os.path.abspath(file)
  267. if not os.path.isfile(file):
  268. raise IOError("File not found: %s" % file)
  269. # first ensure that path exists remotely
  270. target_path = GetBaseRelativePath(path, file, base_path)
  271. if not os.path.exists(target_path):
  272. os.makedirs(target_path)
  273. if verbose:
  274. print "Copying " + file + " to " + target_path
  275. shutil.copy(file, target_path)
  276. def WriteProperties(files, properties_file, url_properties, package):
  277. properties = url_properties
  278. for file in files:
  279. if file.endswith('.complete.mar'):
  280. properties.update(GetMarProperties(file))
  281. with open(properties_file, 'w') as outfile:
  282. properties['packageFilename'] = package
  283. properties['uploadFiles'] = [os.path.abspath(f) for f in files]
  284. json.dump(properties, outfile, indent=4)
  285. if __name__ == '__main__':
  286. host = OptionalEnvironmentVariable('UPLOAD_HOST')
  287. user = OptionalEnvironmentVariable('UPLOAD_USER')
  288. path = OptionalEnvironmentVariable('UPLOAD_PATH')
  289. upload_to_temp_dir = OptionalEnvironmentVariable('UPLOAD_TO_TEMP')
  290. port = OptionalEnvironmentVariable('UPLOAD_PORT')
  291. if port is not None:
  292. port = int(port)
  293. key = OptionalEnvironmentVariable('UPLOAD_SSH_KEY')
  294. post_upload_command = OptionalEnvironmentVariable('POST_UPLOAD_CMD')
  295. if sys.platform == 'win32':
  296. if path is not None:
  297. path = FixupMsysPath(path)
  298. if post_upload_command is not None:
  299. post_upload_command = FixupMsysPath(post_upload_command)
  300. parser = OptionParser(usage="usage: %prog [options] <files>")
  301. parser.add_option("-b", "--base-path",
  302. action="store",
  303. help="Preserve file paths relative to this path when uploading. If unset, all files will be uploaded directly to UPLOAD_PATH.")
  304. parser.add_option("--properties-file",
  305. action="store",
  306. help="Path to the properties file to store the upload properties.")
  307. parser.add_option("--package",
  308. action="store",
  309. help="Name of the main package.")
  310. (options, args) = parser.parse_args()
  311. if len(args) < 1:
  312. print "You must specify at least one file to upload"
  313. sys.exit(1)
  314. if not options.properties_file:
  315. print "You must specify a --properties-file"
  316. sys.exit(1)
  317. if host == "localhost":
  318. if upload_to_temp_dir:
  319. print "Cannot use UPLOAD_TO_TEMP with UPLOAD_HOST=localhost"
  320. sys.exit(1)
  321. if post_upload_command:
  322. # POST_UPLOAD_COMMAND is difficult to extract from the mozharness
  323. # scripts, so just ignore it until it's no longer used anywhere
  324. print "Ignoring POST_UPLOAD_COMMAND with UPLOAD_HOST=localhost"
  325. try:
  326. if host == "localhost":
  327. CopyFilesLocally(path, args, base_path=options.base_path,
  328. package=options.package,
  329. verbose=True)
  330. else:
  331. url_properties = UploadFiles(user, host, path, args,
  332. base_path=options.base_path, port=port, ssh_key=key,
  333. upload_to_temp_dir=upload_to_temp_dir,
  334. post_upload_command=post_upload_command,
  335. package=options.package, verbose=True)
  336. WriteProperties(args, options.properties_file, url_properties, options.package)
  337. except IOError, (strerror):
  338. print strerror
  339. sys.exit(1)