You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

130 lines
5.2KB

  1. #!/usr/bin/env python3
  2. import argparse, sys, shutil, os, subprocess
  3. sys.path.append(os.path.dirname(__file__) + '/lib')
  4. import tamarin
  5. def create_args_parser():
  6. '''Return a new configured ArgumentParser'''
  7. profile_names = tamarin.get_available_profile_names()
  8. parser = argparse.ArgumentParser(description="Generate packages for various GNU/Linux distributions")
  9. # Define available/required arguments and flags
  10. parser.add_argument("project_directory", help="The path to your project to package")
  11. parser.add_argument("-o", "--output", help="The path to the generated packages destination directory", default=".")
  12. parser.add_argument("-p", "--profile", help="The profile to use to package this project (default: debian)", choices=profile_names, default='debian')
  13. parser.add_argument("-a", "--architecture", help="The target architecture for the package (default: amd64)", default='amd64')
  14. parser.add_argument("-b", "--base", help="Use the specified image instead of the profile's one", default='')
  15. parser.add_argument("--rebuild", help="Ignore cache and rebuild container's image", action="store_true", default=False)
  16. parser.add_argument("--debug", help="Will add extra output and start the container in interactive mode", action="store_true", default=False)
  17. parser.add_argument("--cleanup", help="Clear the workspace and remove obsolete Docker images before build", action="store_true", default=False)
  18. parser.add_argument("--override-docker-args", help="Override all 'docker run' arguments. Use '[IMAGE_TAG]', '[PROFILE]' and '[ARCH]' to insert the corresponding values into your command.", default="")
  19. parser.add_argument("--prepare-only", help="Only prepare build environment for the given profile", action="store_true", default=False)
  20. return parser
  21. def build_image(build_workspace, base_image, profile_name, profile, debug=False, rebuild=False):
  22. with open("{:s}/Dockerfile".format(build_workspace), 'w') as dockerfile:
  23. dockerfile.write("FROM {:s}\n".format(base_image))
  24. # Configure "containerbuild" hooks environment
  25. hooks_env = os.environ.copy()
  26. hooks_env["PATH"] = os.environ['PATH'] + ':' + tamarin.get_lib_dir()
  27. # Run hooks
  28. tamarin.run_profile_hooks(profile, 'containerbuild', cwd=build_workspace, env=hooks_env, debug=debug)
  29. image_tag = "tamarin:{:s}_{:s}_{:d}".format(profile_name, base_image.replace(':', '_'), os.getpid())
  30. build_args = [ "build", "-t", image_tag ]
  31. if rebuild:
  32. build_args += [ "--no-cache" ]
  33. tamarin.run_docker(build_args + [build_workspace], debug=debug)
  34. return image_tag
  35. def cleanup(build_workspace=None, debug=False):
  36. if build_workspace == None:
  37. build_workspace = tamarin.get_workspace_subdir('tmp')
  38. # Suppression de l'espace de travail de build
  39. shutil.rmtree(build_workspace, ignore_errors=True)
  40. def validate_args(args):
  41. '''TODO'''
  42. if __name__ == "__main__":
  43. parser = create_args_parser()
  44. args = parser.parse_args()
  45. if args.cleanup:
  46. cleanup(debug=args.debug)
  47. # Verify project directory
  48. project_dir = os.path.abspath(args.project_directory)
  49. output_dir = os.path.abspath(args.output)
  50. # Load build profile
  51. profile = tamarin.load_profile(args.profile, debug=args.debug)
  52. workspace = tamarin.get_workspace_dir()
  53. pid = os.getpid()
  54. build_workspace = tamarin.get_workspace_subdir('tmp/build_{:d}'.format(pid))
  55. base_image = args.base if args.base != '' else profile['profile']['default_image']
  56. image_tag = build_image(build_workspace, base_image, args.profile, profile, debug=args.debug, rebuild=args.rebuild)
  57. if args.prepare_only:
  58. exit()
  59. kwargs = dict()
  60. kwargs['debug'] = args.debug
  61. docker_args = []
  62. # Append custom arguments
  63. if args.override_docker_args != "":
  64. docker_args = args.override_docker_args.replace('[IMAGE_TAG]', image_tag)
  65. docker_args = docker_args.replace('[PROFILE]', args.profile)
  66. docker_args = docker_args.replace('[ARCH]', args.architecture)
  67. else:
  68. docker_args += [ "run", "--rm" ]
  69. # volumes definition
  70. docker_args += [
  71. "-v", "{:s}:/src:ro".format(project_dir),
  72. "-v", "{:s}:/dist".format(output_dir),
  73. "-v", "{:s}:/tamarin/hooks:ro".format(tamarin.get_hooks_dir()),
  74. "-v", "{:s}:/tamarin/lib:ro".format(tamarin.get_lib_dir()),
  75. "-v", "{:s}:/tamarin/profiles:ro".format(tamarin.get_profiles_dir())
  76. ]
  77. # Use environment proxy if defined
  78. for proxy_var in ['HTTP_PROXY', 'HTTPS_PROXY', 'http_proxy', 'https_proxy']:
  79. if proxy_var in os.environ:
  80. docker_args += ["-e", "{:s}={:s}".format(proxy_var, os.environ[proxy_var])]
  81. if args.debug:
  82. kwargs['pty'] = True
  83. docker_args += ["-it", image_tag, "/bin/sh"]
  84. helper_cmd = " ".join(["/usr/bin/python3", "/tamarin/lib/build.py", args.profile, args.architecture])
  85. print("Executer '{:s}' pour lancer la construction du paquet.".format(helper_cmd))
  86. else:
  87. docker_args += [image_tag, "/usr/bin/python3", "/tamarin/lib/build.py", args.profile, args.architecture]
  88. # Start container
  89. tamarin.run_docker(docker_args, **kwargs)
  90. cleanup(build_workspace, debug=args.debug)