├── .gitignore ├── LICENSE.md ├── README.md ├── aospdocker ├── __init__.py ├── aospconfig.py ├── aospdocker.py ├── dockerclient.py └── dockerfile.py └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | 5 | # C extensions 6 | *.so 7 | 8 | # Distribution / packaging 9 | .Python 10 | env/ 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | *.egg-info/ 23 | .installed.cfg 24 | *.egg 25 | 26 | # PyInstaller 27 | # Usually these files are written by a python script from a template 28 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 29 | *.manifest 30 | *.spec 31 | 32 | # Installer logs 33 | pip-log.txt 34 | pip-delete-this-directory.txt 35 | 36 | # Unit test / coverage reports 37 | htmlcov/ 38 | .tox/ 39 | .coverage 40 | .coverage.* 41 | .cache 42 | nosetests.xml 43 | coverage.xml 44 | *,cover 45 | 46 | # Translations 47 | *.mo 48 | *.pot 49 | 50 | # Django stuff: 51 | *.log 52 | 53 | # Sphinx documentation 54 | docs/_build/ 55 | 56 | # PyBuilder 57 | target/ -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2015 Mathias Garbe 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # aosp-docker 2 | 3 | A Python 2/3 script which can be used to build various AOSP versions inside a docker container. 4 | 5 | Very early state, expect things to change and break with new commits. 6 | 7 | ## Dependencies 8 | 9 | * docker 1.6 10 | * python: docker-py 1.3 11 | 12 | ## Why? 13 | 14 | In order to compile AOSP a very specific tool chain is needed. Bash is needed for every version, Android 4.0 needs gcc 4.4 and Oracle JDK 6, Android 5.0 gcc 4.8 and OpenJDK 7. Using a virtual machine for building has a large overhead, most developers will use a full Ubuntu installation with XServer and everything, which can take up to 20 Gb disk space and comes with processor and memory overhead. Having to work on and build multiple different AOSP versions I opted to hack together this python script which uses docker to build the different versions. 15 | 16 | ## How? 17 | 18 | The container image already has the needed tool chain installed and could be used without a script. But as we do not want to work inside the container the script uses `docker exec` to run commands inside the container. In order to save the bash environment every `aosp exec` command is wrapped: 19 | 20 | source /env.bash && cd {dir} && {cmd} && declare -p | sed -e \'/declare -[a-z]*r/d\' > /env.bash && declare -f >> /env.bash 21 | 22 | This will first source the saved environment, change to the requested directory, executes the command and then saves the environment (including functions) back to disk. The `sed` regex is needed to only save environment variables which are not read-only. 23 | 24 | When dropping into a bash with `aosp bash`, the script will execute `/bin/bash --rcfile /rc.bash`. This rcfile will trap the exit signal in order to save the environment after the bash is closed: 25 | 26 | trap "declare -p | sed -e '/declare -[a-z]*r/d' > /env.bash && declare -f >> /env.bash" EXIT 27 | 28 | The script will create a user inside the docker container with the same uid/gid as your user, which will be used when interacting with the `exec` and `bash` commands. In case you want root access, `aosp root exec` and `aosp root bash` can be used, but the environment will not be saved. 29 | 30 | ## Todo and Known Issues 31 | 32 | * Dockerfiles should not be generated at runtime, but maybe checked into the repository 33 | * git and bash configs are currently not copied to the container 34 | 35 | ## Usage 36 | Usage: aosp [COMMAND] [arg...] 37 | Commands: 38 | init Initialize a container in current directory (should be AOSP dir) 39 | exec Executes a command inside the aosp build container 40 | bash Starts a bash shell inside the container 41 | clean Removes container 42 | info Shows information about the aosp container 43 | 44 | For root access please use `root exec` and `root bash`. 45 | 46 | ## Example usage 47 | 48 | ### Download AOSP 4.4.4 49 | ~ $> mkdir ~/aosp && cd ~/aosp 50 | ~/aosp $> aosp init 4.4 51 | ~/aosp $> aosp exec repo init -u https://android.googlesource.com/platform/manifest/ -b android-4.4.4_r2 52 | ~/aosp $> aosp exec repo sync 53 | 54 | ### Build AOSP 55 | ~/aosp $> aosp exec . build/envsetup.sh 56 | ~/aosp $> aosp exec lunch 57 | ~/aosp $> aosp exec make -j5 58 | 59 | ### Inside a sub directory 60 | ~/aosp $> cd packages/apps/Calculator 61 | ~/aosp/packages/apps/Calculator $> aosp exec mmm 62 | 63 | ### Drop into a bash and continue building 64 | ~/aosp $> aosp exec lunch 65 | ~/aosp $> aosp bash 66 | /aosp# make -j5 67 | 68 | ### Enable X forwarding and start emulator 69 | ~/aosp $> xhost + 70 | ~/aosp $> aosp exec emulator 71 | 72 | ### Remove container 73 | ~/aosp $> aosp clean 74 | -------------------------------------------------------------------------------- /aospdocker/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/psde/aosp-docker/67d91a9912b53337a2958fd9fe5a0b22a5e78ca2/aospdocker/__init__.py -------------------------------------------------------------------------------- /aospdocker/aospconfig.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python2 2 | 3 | # Copyright 2015 Mathias Garbe 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | import os 18 | import sys 19 | import shutil 20 | 21 | from configparser import SafeConfigParser 22 | 23 | 24 | class AospConfig: 25 | def __init__(self, config_directory): 26 | self.config_directory = config_directory 27 | self.config_file = os.path.join(config_directory, 'config') 28 | self.dirty = False 29 | 30 | self.config = SafeConfigParser() 31 | self.config.read(self.config_file) 32 | 33 | def write(self): 34 | if not self.dirty: 35 | return 36 | 37 | # Check if dir exists 38 | if os.path.isdir(self.config_directory) == False: 39 | os.makedirs(self.config_directory) 40 | 41 | with open(self.config_file, 'w') as f: 42 | self.config.write(f) 43 | 44 | def set(self, section, option, value): 45 | if not self.config.has_section(section): 46 | self.config.add_section(section) 47 | 48 | self.config.set(section, option, value) 49 | self.dirty = True 50 | 51 | def get(self, section, option): 52 | try: 53 | return self.config.get(section, option) 54 | except Exception: 55 | return None 56 | 57 | def remove_option(self, section, option): 58 | try: 59 | self.config.remove_option(section, option) 60 | self.dirty = True 61 | return True 62 | except Exception: 63 | return False 64 | 65 | def remove_section(self, section): 66 | try: 67 | self.config.remove_section(section) 68 | self.dirty = True 69 | return True 70 | except Exception: 71 | return False 72 | 73 | def remove_configuration(self): 74 | self.dirty = False 75 | self.config = SafeConfigParser() 76 | shutil.rmtree(self.config_directory) 77 | -------------------------------------------------------------------------------- /aospdocker/aospdocker.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python2 2 | 3 | # Copyright 2015 Mathias Garbe 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from __future__ import print_function, absolute_import 18 | import os 19 | import sys 20 | import shutil 21 | import pwd 22 | import getpass 23 | import operator 24 | from aospdocker.dockerclient import DockerClient 25 | from aospdocker.aospconfig import AospConfig 26 | from aospdocker.dockerfile import Dockerfile 27 | 28 | 29 | class AospDocker: 30 | LoadEnv = 'source /env.bash' 31 | SaveEnv = 'declare -p | sed -e \'/declare -[a-z]*r/d\' > /env.bash && declare -f >> /env.bash' 32 | 33 | def __init__(self): 34 | self.versions = Dockerfile.build_versions() 35 | self.client = DockerClient() 36 | 37 | self.base_directory = self.find_config_directory() 38 | if self.base_directory is None: 39 | self.base_directory = os.getcwd() 40 | 41 | self.relative_directory = os.path.relpath(os.getcwd(), self.base_directory) 42 | 43 | self.config = AospConfig(os.path.join(self.base_directory, '.aosp-docker')) 44 | 45 | self.main() 46 | 47 | self.config.write() 48 | 49 | def find_config_directory(self): 50 | current_path = os.getcwd() 51 | old_path = current_path 52 | while True: 53 | if os.path.isfile(os.path.join(current_path, '.aosp-docker', 'config')) == True: 54 | return current_path 55 | 56 | current_path = os.path.abspath(os.path.join(current_path, os.pardir)) 57 | if old_path == current_path: 58 | break 59 | old_path = current_path 60 | 61 | return None 62 | 63 | def check_or_build_image(self, dockerfile): 64 | image = None 65 | images = self.client.get_images() 66 | try: 67 | image = list(filter(lambda image: image.repo.startswith(dockerfile.get_image_name()), images))[0] 68 | except Exception: 69 | pass 70 | 71 | if image is None: 72 | print('Image not found, building...') 73 | self.client.build_image(dockerfile) 74 | 75 | return True 76 | 77 | def get_container(self): 78 | container_id = self.config.get('main', 'container-id') 79 | user = self.config.get('main', 'user') 80 | 81 | if container_id is None or user is None: 82 | return None 83 | 84 | container = self.client.get_container_by_id(container_id) 85 | if container is None: 86 | self.config.remove_option('main', 'container-id') 87 | return None 88 | 89 | if not container.up: 90 | print('Container stopped, starting...', end='') 91 | self.client.start_container(container.id) 92 | print('done.') 93 | 94 | return container 95 | 96 | def print_needs_container(self): 97 | print('Container not found, please use \'aosp init\' first') 98 | 99 | def print_usage(self): 100 | print('Usage: aosp [COMMAND] [arg...]') 101 | print('Commands:') 102 | print('\tinit\tInitialize a container in current directory (should be AOSP dir)') 103 | print('\texec\tExecutes a command inside the aosp build container') 104 | print('\tbash\tStarts a bash shell inside the container') 105 | print('\tclean\tRemoves container') 106 | print('\tinfo\tShows information about the aosp container') 107 | print('') 108 | print('For root access please use `root exec` and `root bash`.') 109 | 110 | def main(self): 111 | if len(sys.argv) == 1: 112 | print('Not enough parameters') 113 | self.print_usage() 114 | return 115 | 116 | container = self.get_container() 117 | 118 | cmd = sys.argv[1] 119 | root = False 120 | 121 | if cmd == 'root': 122 | root = True 123 | if len(sys.argv) == 2: 124 | print('Not enough parameters') 125 | self.print_usage() 126 | return 127 | cmd = sys.argv[2] 128 | 129 | if cmd == 'init': 130 | self.init() 131 | elif cmd == 'exec' or cmd == 'execute': 132 | if container is None: 133 | return self.print_needs_container() 134 | self.execute(root) 135 | elif cmd == 'bash': 136 | if container is None: 137 | return self.print_needs_container() 138 | self.bash(root) 139 | elif cmd == 'clean': 140 | self.clean() 141 | elif cmd == 'info': 142 | self.info() 143 | else: 144 | print('Unrecognized command') 145 | self.print_usage() 146 | 147 | def print_init_usage(self): 148 | print('Usage: aosp init [VERSION]') 149 | print('Supported versions: ') 150 | for key, value in sorted(self.versions.items(), key=operator.itemgetter(0)): 151 | print("\t{key}\t\tbased on {base}".format(key=key, base=value.base)) 152 | 153 | def init(self): 154 | if len(sys.argv) == 2: 155 | print('Not enough parameters') 156 | self.print_init_usage() 157 | return 158 | 159 | version = sys.argv[2] 160 | if version not in self.versions: 161 | print('Did not recognize Android version.') 162 | self.print_init_usage() 163 | return 164 | 165 | dockerfile = self.versions[version] 166 | self.check_or_build_image(dockerfile) 167 | 168 | container = self.get_container() 169 | 170 | if container is not None: 171 | print('Container already initialized.') 172 | return 173 | 174 | print('Setting up new container...', end='') 175 | 176 | volumes = {'/tmp/.X11-unix': '/tmp/.X11-unix', os.getcwd(): '/aosp'} 177 | env = ['DISPLAY=unix{display}'.format(display=os.environ['DISPLAY'])] 178 | user = pwd.getpwnam(getpass.getuser()) 179 | container = self.client.create_container(dockerfile=dockerfile, command='/bin/bash', environment=env, volumes=volumes) 180 | 181 | # Add user to container 182 | self.client.interactive(container.id, '/bin/bash -c "useradd -b / -d / -M -U -u {uid} -s /bin/bash {user}"' 183 | .format(uid=user.pw_uid, user=user.pw_name)) 184 | 185 | # Save the environment for the first time 186 | self.client.interactive(container.id, 'su - {user} -c /bin/bash -c "{saveEnv}"' 187 | .format(saveEnv=AospDocker.SaveEnv, user=user.pw_name)) 188 | 189 | self.config.set('main', 'container-id', container.id) 190 | self.config.set('main', 'user', user.pw_name) 191 | 192 | print('done: {id}'.format(id=container.id)) 193 | print('You can now use aosp exec [COMMAND]') 194 | print('In order to use X11, you need to enable access via \'xhost +\'') 195 | 196 | pass 197 | 198 | def execute(self, root=False): 199 | container = self.get_container() 200 | user = self.config.get('main', 'user') 201 | 202 | if len(sys.argv) == 2: 203 | print('Not enough parameters.') 204 | print('Usage: aosp exec [COMMAND...]') 205 | return 206 | 207 | cmd = " ".join(sys.argv[2:]) 208 | 209 | if root: 210 | self.client.interactive(container.id, '/bin/bash -ic "{cmd}"'.format(cmd=cmd)) 211 | else: 212 | # Execute command as user 213 | self.client.interactive(container.id, 'su - {user} -c "{loadEnv} && cd /aosp/{rel_dir} && {cmd} && {saveEnv}"' 214 | .format(user=user, rel_dir=self.relative_directory, loadEnv=AospDocker.LoadEnv, cmd=cmd, saveEnv=AospDocker.SaveEnv)) 215 | 216 | def bash(self, root=False): 217 | container = self.get_container() 218 | user = self.config.get('main', 'user') 219 | 220 | if root: 221 | self.client.interactive(container.id, '/bin/bash') 222 | else: 223 | # Change directory and save env 224 | self.client.interactive(container.id, 'su - {user} -c "{loadEnv} && cd /aosp/{rel_dir} && {saveEnv}"' 225 | .format(user=user, rel_dir=self.relative_directory, loadEnv=AospDocker.LoadEnv, saveEnv=AospDocker.SaveEnv)) 226 | 227 | # Open a (trapped) shell using rc.bash 228 | self.client.interactive(container.id, 'su - {user} -c "/bin/bash --rcfile /rc.bash"' 229 | .format(user=user)) 230 | 231 | def clean(self): 232 | container = self.get_container() 233 | 234 | if container is None: 235 | print('Container not initialized.') 236 | self.config.remove_section('main') 237 | return 238 | 239 | print('Container found, trying to remove...', end='') 240 | self.client.remove_container(container.id) 241 | self.config.remove_section('main') 242 | print('done.') 243 | 244 | print('Removing configuration directory...', end='') 245 | self.config.remove_configuration() 246 | print('done.') 247 | 248 | def info(self): 249 | container = self.get_container() 250 | 251 | if container is None: 252 | print('No container found, use aosp init first.') 253 | return 254 | 255 | print('Container Information:') 256 | print('Id:\t{id}'.format(id=container.id)) 257 | print('Image:\t{image}'.format(image=container.image)) 258 | print('Names:\t{names}'.format(names=container.names)) 259 | print('Status:\t{status}'.format(status=container.status)) 260 | 261 | print('\nAOSP Docker Information:') 262 | print('User:\t{user}'.format(user=self.config.get('main', 'user'))) 263 | print('Dir:\t{dir}'.format(dir=self.base_directory)) 264 | print('RelDir:\t{dir}'.format(dir=self.relative_directory)) 265 | print('Config:\t{config}'.format(config=self.config.config_directory)) 266 | 267 | 268 | def cmd(): 269 | AospDocker() 270 | 271 | if __name__ == "__main__": 272 | cmd() 273 | -------------------------------------------------------------------------------- /aospdocker/dockerclient.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Mathias Garbe 2 | # 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 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 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. 14 | 15 | from __future__ import absolute_import, print_function 16 | from future.utils import iteritems 17 | import docker 18 | import subprocess 19 | import os 20 | import io 21 | import json 22 | from aospdocker.dockerfile import Dockerfile 23 | 24 | 25 | class Container(): 26 | def __init__(self, info): 27 | self.id = info['Id'] 28 | self.image = info['Image'] 29 | self.names = info['Names'] 30 | self.created = info['Created'] 31 | self.up = False if info['Status'].lower().startswith('exited') else True 32 | self.status = info['Status'] 33 | 34 | def __repr__(self): 35 | return self.__str__() 36 | 37 | def __str__(self): 38 | attrs = ', '.join("%s: %s" % item for item in vars(self).items()) 39 | return '<{attrs}>'.format(attrs=attrs) 40 | 41 | 42 | class Image(): 43 | def __init__(self, info): 44 | self.id = info['Id'] 45 | self.parent = info['ParentId'] 46 | self.created = info['Created'] 47 | self.repo = info['RepoTags'][0] 48 | self.repoTags = info['RepoTags'] 49 | 50 | def __repr__(self): 51 | return self.__str__() 52 | 53 | def __str__(self): 54 | attrs = ', '.join("%s: %s" % item for item in vars(self).items()) 55 | return '<{attrs}>'.format(attrs=attrs) 56 | 57 | 58 | class DockerClient(): 59 | def __init__(self): 60 | self.client = docker.Client(**docker.utils.kwargs_from_env()) 61 | 62 | def get_images(self): 63 | imageInfos = self.client.images() 64 | images = [] 65 | for info in imageInfos: 66 | images.append(Image(info)) 67 | return images 68 | 69 | def remove_image(self, id): 70 | return self.client.remove_image(image=id) 71 | 72 | def build_image(self, dockerfile): 73 | if isinstance(dockerfile, Dockerfile) == False: 74 | raise TypeError('{cls} is not derrived from Dockerfile'.format(cls=dockerfile)) 75 | 76 | fileobj = io.BytesIO(dockerfile.build_dockerfile().encode('utf-8')) 77 | for line in self.client.build(fileobj=fileobj, rm=True, forcerm=True, tag=dockerfile.get_image_name()): 78 | jobj = json.loads(line.decode('utf-8')) 79 | 80 | if 'stream' in jobj: 81 | print(jobj['stream'], end='') 82 | elif 'status' in jobj: 83 | print('{status} {progress}'.format(status=jobj['status'], progress=jobj['progress'])) 84 | else: 85 | print(line) 86 | 87 | def get_containers(self): 88 | containerInfos = self.client.containers(all=True) 89 | containers = [] 90 | for info in containerInfos: 91 | containers.append(Container(info)) 92 | return containers 93 | 94 | def get_container_by_id(self, id): 95 | containers = self.get_containers() 96 | try: 97 | return list(filter(lambda container: container.id == id, containers))[0] 98 | except Exception: 99 | return None 100 | 101 | def remove_container(self, id): 102 | return self.client.remove_container(container=id, force=True) 103 | 104 | def create_container(self, dockerfile, command, environment, volumes): 105 | if isinstance(dockerfile, Dockerfile) == False: 106 | raise TypeError('{cls} is not derrived from Dockerfile'.format(cls=dockerfile)) 107 | 108 | container_volumes = [] 109 | binds = {} 110 | for key, value in iteritems(volumes): 111 | binds[key] = {'bind': value, 'ro': False} 112 | container_volumes.append(value) 113 | 114 | container = self.client.create_container(tty=True, detach=True, image=dockerfile.get_image_name(), command=command, volumes=container_volumes, environment=environment) 115 | self.client.start(privileged=True, network_mode='host', container=container['Id'], binds=binds) 116 | return self.get_container_by_id(container['Id']) 117 | 118 | def start_container(self, id): 119 | return self.client.start(container=id) 120 | 121 | def interactive(self, id, command): 122 | # docker-py has now way to execute a command interactively 123 | subprocess.call('docker exec -it {id} {command}'.format(id=id, command=command), shell=True) 124 | -------------------------------------------------------------------------------- /aospdocker/dockerfile.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Mathias Garbe 2 | # 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 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 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. 14 | 15 | 16 | class Dockerfile(): 17 | def __init__(self, version, base, packages, java, misc=''): 18 | self.version = version 19 | self.base = base 20 | self.packages = packages 21 | self.java = java 22 | self.misc = misc 23 | 24 | def get_image_name(self): 25 | return 'aosp-docker-{version}'.format(version=self.version) 26 | 27 | def build_dockerfile(self): 28 | misc = '' 29 | if self.misc != '': 30 | misc = "RUN {cmd}".format(cmd=self.misc) 31 | d = ("FROM {base}\n" 32 | "MAINTAINER Mathias Garbe \n" 33 | "RUN touch /env.bash && echo 'source /env.bash' > /rc.bash && echo 'cd $PWD' >> /rc.bash && echo \"trap \\\"declare -p | sed -e '/declare -[a-z]*r/d' > /env.bash && declare -f >> /env.bash\\\" EXIT\" >> /rc.bash\n" 34 | "RUN chmod 777 /env.bash && chmod 777 /rc.bash\n" 35 | "RUN apt-get update\n" 36 | "RUN {java}\n" 37 | "RUN echo \"dash dash/sh boolean false\" | debconf-set-selections && dpkg-reconfigure -p critical dash\n" 38 | "RUN apt-get install -y bash-completion vim wget {packages}\n" 39 | "ADD https://commondatastorage.googleapis.com/git-repo-downloads/repo /usr/local/bin/\n" 40 | "RUN chmod 755 /usr/local/bin/*\n" 41 | "{misc}\n" 42 | "VOLUME [\"/tmp/ccache\", \"/aosp\"]\n" 43 | "ENV USE_CCACHE 1\n" 44 | "ENV CCACHE_DIR /tmp/ccache\n" 45 | "RUN apt-get clean && rm -rf /var/tmp/*\n").format(base=self.base, java=self.java, packages=self.packages, misc=misc) 46 | return d 47 | 48 | @staticmethod 49 | def build_versions(): 50 | java6_lucid = 'apt-get install -y python-software-properties && add-apt-repository ppa:sun-java-community-team/sun-java6 && apt-get update && echo sun-java6-jdk shared/accepted-sun-dlj-v1-1 select true | /usr/bin/debconf-set-selections && apt-get install -y sun-java6-jdk' 51 | java6_precise = 'echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" >> /etc/apt/sources.list.d/webupd8.list && apt-key adv --keyserver keyserver.ubuntu.com --recv-keys EEA14886 && echo oracle-java6-installer shared/accepted-oracle-license-v1-1 select true | debconf-set-selections && apt-get update && apt-get -y install oracle-java6-installer oracle-java6-set-default' 52 | java6_trusty = 'echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu trusty main" >> /etc/apt/sources.list.d/webupd8.list && apt-key adv --keyserver keyserver.ubuntu.com --recv-keys EEA14886 && echo oracle-java6-installer shared/accepted-oracle-license-v1-1 select true | debconf-set-selections && apt-get update && apt-get -y install oracle-java6-installer oracle-java6-set-default' 53 | java7 = 'apt-get install -y openjdk-7-jdk' 54 | 55 | misc_git = 'apt-get install -y python-software-properties && add-apt-repository ppa:git-core/ppa && apt-get update && apt-get install -y git' 56 | 57 | v = {} 58 | v['4.0'] = Dockerfile('4.0', 'ubuntu:10.04', 'bash-completion uboot-mkimage gnupg flex bison gperf build-essential zip curl zlib1g-dev libc6-dev lib32ncurses5-dev ia32-libs x11proto-core-dev libx11-dev lib32readline5-dev lib32z-dev libgl1-mesa-dev g++-multilib mingw32 tofrodos python-markdown libxml2-utils xsltproc', java6_lucid, misc_git) 59 | v['4.1'] = Dockerfile('4.1', 'ubuntu:12.04', 'bash-completion uboot-mkimage bc bison bsdmainutils build-essential curl flex g++-multilib gcc-multilib git gnupg gperf lib32ncurses5-dev lib32readline-gplv2-dev lib32z1-dev libesd0-dev libncurses5-dev libsdl1.2-dev libwxgtk2.8-dev libxml2-utils lzop pngcrush schedtool xsltproc zip zlib1g-dev', java6_precise) 60 | v['4.2'] = v['4.1'] 61 | v['4.3'] = v['4.2'] 62 | v['4.4'] = Dockerfile('4.4', 'ubuntu:14.04', 'bash-completion u-boot-tools bc bison bsdmainutils build-essential curl flex g++-multilib gcc-multilib git gnupg gperf lib32ncurses5-dev lib32readline-gplv2-dev lib32z1-dev libesd0-dev libncurses5-dev libsdl1.2-dev libwxgtk2.8-dev libxml2-utils lzop pngcrush schedtool xsltproc zip zlib1g-dev', java6_trusty) 63 | v['5.0'] = Dockerfile('5.0', 'ubuntu:14.04', 'bash-completion u-boot-tools bc bison bsdmainutils build-essential curl flex g++-multilib gcc-multilib git gnupg gperf lib32ncurses5-dev lib32readline-gplv2-dev lib32z1-dev libesd0-dev libncurses5-dev libsdl1.2-dev libwxgtk2.8-dev libxml2-utils lzop pngcrush schedtool xsltproc zip zlib1g-dev', java7) 64 | return v 65 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Mathias Garbe 2 | # 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 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 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. 14 | 15 | from setuptools import setup, find_packages 16 | from codecs import open 17 | from os import path 18 | 19 | 20 | dir = path.abspath(path.dirname(__file__)) 21 | with open(path.join(dir, 'README.md'), encoding='utf-8') as f: 22 | readme = f.read() 23 | 24 | setup( 25 | name='aospdocker', 26 | 27 | version='0.1.0', 28 | 29 | description='AOSP Docker', 30 | long_description=readme, 31 | 32 | url='https://github.com/inovex/aosp-docker', 33 | 34 | author='Mathias Garbe', 35 | author_email='mathias.garbe@inovex.de', 36 | 37 | license='Apache', 38 | 39 | classifiers=[ 40 | 'Development Status :: 2 - Pre-Alpha', 41 | 42 | 'Intended Audience :: Developers', 43 | 'Topic :: Software Development :: Build Tools', 44 | 45 | 'Operating System :: POSIX :: Linux', 46 | 47 | 'License :: OSI Approved :: Apache Software License', 48 | 49 | 'Programming Language :: Python :: 2', 50 | 'Programming Language :: Python :: 2.6', 51 | 'Programming Language :: Python :: 2.7', 52 | 'Programming Language :: Python :: 3', 53 | ], 54 | 55 | keywords='aosp android docker development', 56 | 57 | packages=['aospdocker'], 58 | 59 | install_requires=['docker-py', 'future'], 60 | 61 | entry_points={ 62 | 'console_scripts': [ 63 | 'aosp=aospdocker.aospdocker:cmd', 64 | ], 65 | }, 66 | ) 67 | --------------------------------------------------------------------------------