deploy_docs.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. #!/usr/bin/env python3
  2. #
  3. # CI script to deploy docs to a webserver. Not useful outside of CI environment
  4. #
  5. #
  6. # Copyright 2020 Espressif Systems (Shanghai) PTE LTD
  7. #
  8. # Licensed under the Apache License, Version 2.0 (the "License");
  9. # you may not use this file except in compliance with the License.
  10. # You may obtain a copy of the License at
  11. #
  12. # http://www.apache.org/licenses/LICENSE-2.0
  13. #
  14. # Unless required by applicable law or agreed to in writing, software
  15. # distributed under the License is distributed on an "AS IS" BASIS,
  16. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17. # See the License for the specific language governing permissions and
  18. # limitations under the License.
  19. #
  20. import glob
  21. import os
  22. import os.path
  23. import re
  24. import stat
  25. import subprocess
  26. import sys
  27. import tarfile
  28. import packaging.version
  29. def env(variable, default=None):
  30. """ Shortcut to return the expanded version of an environment variable """
  31. return os.path.expandvars(os.environ.get(variable, default) if default else os.environ[variable])
  32. # import sanitize_version from the docs directory, shared with here
  33. sys.path.append(os.path.join(env('IDF_PATH'), 'docs'))
  34. from sanitize_version import sanitize_version # noqa
  35. def main():
  36. # if you get KeyErrors on the following lines, it's probably because you're not running in Gitlab CI
  37. git_ver = env('GIT_VER') # output of git describe --always
  38. ci_ver = env('CI_COMMIT_REF_NAME', git_ver) # branch or tag we're building for (used for 'release' & URL)
  39. version = sanitize_version(ci_ver)
  40. print('Git version: {}'.format(git_ver))
  41. print('CI Version: {}'.format(ci_ver))
  42. print('Deployment version: {}'.format(version))
  43. if not version:
  44. raise RuntimeError('A version is needed to deploy')
  45. build_dir = env('DOCS_BUILD_DIR') # top-level local build dir, where docs have already been built
  46. if not build_dir:
  47. raise RuntimeError('Valid DOCS_BUILD_DIR is needed to deploy')
  48. url_base = env('DOCS_DEPLOY_URL_BASE') # base for HTTP URLs, used to print the URL to the log after deploying
  49. docs_server = env('DOCS_DEPLOY_SERVER') # ssh server to deploy to
  50. docs_user = env('DOCS_DEPLOY_SERVER_USER')
  51. docs_path = env('DOCS_DEPLOY_PATH') # filesystem path on DOCS_SERVER
  52. if not docs_server:
  53. raise RuntimeError('Valid DOCS_DEPLOY_SERVER is needed to deploy')
  54. if not docs_user:
  55. raise RuntimeError('Valid DOCS_DEPLOY_SERVER_USER is needed to deploy')
  56. docs_server = '{}@{}'.format(docs_user, docs_server)
  57. if not docs_path:
  58. raise RuntimeError('Valid DOCS_DEPLOY_PATH is needed to deploy')
  59. print('DOCS_DEPLOY_SERVER {} DOCS_DEPLOY_PATH {}'.format(docs_server, docs_path))
  60. tarball_path, version_urls = build_doc_tarball(version, git_ver, build_dir)
  61. deploy(version, tarball_path, docs_path, docs_server)
  62. print('Docs URLs:')
  63. doc_deploy_type = os.getenv('TYPE')
  64. for vurl in version_urls:
  65. language, _, target = vurl.split('/')
  66. tag = '{}_{}'.format(language, target)
  67. url = '{}/{}/index.html'.format(url_base, vurl) # (index.html needed for the preview server)
  68. url = re.sub(r'([^:])//', r'\1/', url) # get rid of any // that isn't in the https:// part
  69. print('[document {}][{}] {}'.format(doc_deploy_type, tag, url))
  70. # note: it would be neater to use symlinks for stable, but because of the directory order
  71. # (language first) it's kind of a pain to do on a remote server, so we just repeat the
  72. # process but call the version 'stable' this time
  73. if is_stable_version(version):
  74. print('Deploying again as stable version...')
  75. tarball_path, version_urls = build_doc_tarball('stable', git_ver, build_dir)
  76. deploy('stable', tarball_path, docs_path, docs_server)
  77. def deploy(version, tarball_path, docs_path, docs_server):
  78. def run_ssh(commands):
  79. """ Log into docs_server and run a sequence of commands using ssh """
  80. print('Running ssh: {}'.format(commands))
  81. subprocess.run(['ssh', '-o', 'BatchMode=yes', docs_server, '-x', ' && '.join(commands)], check=True)
  82. # copy the version tarball to the server
  83. run_ssh(['mkdir -p {}'.format(docs_path)])
  84. print('Running scp {} to {}'.format(tarball_path, '{}:{}'.format(docs_server, docs_path)))
  85. subprocess.run(['scp', '-B', tarball_path, '{}:{}'.format(docs_server, docs_path)], check=True)
  86. tarball_name = os.path.basename(tarball_path)
  87. run_ssh(['cd {}'.format(docs_path),
  88. 'rm -rf ./*/{}'.format(version), # remove any pre-existing docs matching this version
  89. 'tar -zxvf {}'.format(tarball_name), # untar the archive with the new docs
  90. 'rm {}'.format(tarball_name)])
  91. # Note: deleting and then extracting the archive is a bit awkward for updating stable/latest/etc
  92. # as the version will be invalid for a window of time. Better to do it atomically, but this is
  93. # another thing made much more complex by the directory structure putting language before version...
  94. def build_doc_tarball(version, git_ver, build_dir):
  95. """ Make a tar.gz archive of the docs, in the directory structure used to deploy as
  96. the given version """
  97. version_paths = []
  98. tarball_path = '{}/{}.tar.gz'.format(build_dir, version)
  99. # find all the 'html/' directories under build_dir
  100. html_dirs = glob.glob('{}/**/html/'.format(build_dir), recursive=True)
  101. print('Found %d html directories' % len(html_dirs))
  102. pdfs = glob.glob('{}/**/latex/build/*.pdf'.format(build_dir), recursive=True)
  103. print('Found %d PDFs in latex directories' % len(pdfs))
  104. # add symlink for stable and latest and adds them to PDF blob
  105. symlinks = create_and_add_symlinks(version, git_ver, pdfs)
  106. def not_sources_dir(ti):
  107. """ Filter the _sources directories out of the tarballs """
  108. if ti.name.endswith('/_sources'):
  109. return None
  110. ti.mode |= stat.S_IWGRP # make everything group-writeable
  111. return ti
  112. try:
  113. os.remove(tarball_path)
  114. except OSError:
  115. pass
  116. with tarfile.open(tarball_path, 'w:gz') as tarball:
  117. for html_dir in html_dirs:
  118. # html_dir has the form '<ignored>/<language>/<target>/html/'
  119. target_dirname = os.path.dirname(os.path.dirname(html_dir))
  120. target = os.path.basename(target_dirname)
  121. language = os.path.basename(os.path.dirname(target_dirname))
  122. # when deploying, we want the top-level directory layout 'language/version/target'
  123. archive_path = '{}/{}/{}'.format(language, version, target)
  124. print("Archiving '{}' as '{}'...".format(html_dir, archive_path))
  125. tarball.add(html_dir, archive_path, filter=not_sources_dir)
  126. version_paths.append(archive_path)
  127. for pdf_path in pdfs:
  128. # pdf_path has the form '<ignored>/<language>/<target>/latex/build'
  129. latex_dirname = os.path.dirname(pdf_path)
  130. pdf_filename = os.path.basename(pdf_path)
  131. target_dirname = os.path.dirname(os.path.dirname(latex_dirname))
  132. target = os.path.basename(target_dirname)
  133. language = os.path.basename(os.path.dirname(target_dirname))
  134. # when deploying, we want the layout 'language/version/target/pdf'
  135. archive_path = '{}/{}/{}/{}'.format(language, version, target, pdf_filename)
  136. print("Archiving '{}' as '{}'...".format(pdf_path, archive_path))
  137. tarball.add(pdf_path, archive_path)
  138. for symlink in symlinks:
  139. os.unlink(symlink)
  140. return (os.path.abspath(tarball_path), version_paths)
  141. def create_and_add_symlinks(version, git_ver, pdfs):
  142. """ Create symbolic links for PDFs for 'latest' and 'stable' releases """
  143. symlinks = []
  144. if 'stable' in version or 'latest' in version:
  145. for pdf_path in pdfs:
  146. symlink_path = pdf_path.replace(git_ver, version)
  147. os.symlink(pdf_path, symlink_path)
  148. symlinks.append(symlink_path)
  149. pdfs.extend(symlinks)
  150. print('Found %d PDFs in latex directories after adding symlink' % len(pdfs))
  151. return symlinks
  152. def is_stable_version(version):
  153. """ Heuristic for whether this is the latest stable release """
  154. if not version.startswith('v'):
  155. return False # branch name
  156. if '-' in version:
  157. return False # prerelease tag
  158. git_out = subprocess.check_output(['git', 'tag', '-l']).decode('utf-8')
  159. versions = [v.strip() for v in git_out.split('\n')]
  160. versions = [v for v in versions if re.match(r'^v[\d\.]+$', v)] # include vX.Y.Z only
  161. versions = [packaging.version.parse(v) for v in versions]
  162. max_version = max(versions)
  163. if max_version.public != version[1:]:
  164. print('Stable version is v{}. This version is {}.'.format(max_version.public, version))
  165. return False
  166. else:
  167. print('This version {} is the stable version'.format(version))
  168. return True
  169. if __name__ == '__main__':
  170. main()