├── .gitignore ├── LICENSE ├── Makefile ├── README.md ├── apperror └── error.go ├── config └── config.go ├── osx-builder.go ├── pkg ├── render │ ├── render.go │ └── render_test.go ├── unzipit │ ├── fixtures │ │ ├── cfgdrv.iso │ │ ├── filetest.zip │ │ ├── tar-without-directory-entries.tar.gz │ │ ├── test.tar │ │ ├── test.tar.bzip2 │ │ ├── test.tar.gz │ │ ├── test.zip │ │ └── test2.tar.gz │ ├── unzipit.go │ └── unzipit_test.go └── vmware │ ├── fusion7.go │ ├── vmware.go │ └── vmx.go └── vms ├── assert_test.go ├── error.go ├── fixtures └── test.box ├── image.go ├── image_test.go ├── vm.go └── web.go /.gitignore: -------------------------------------------------------------------------------- 1 | build 2 | dist 3 | go-osx-builder 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | 375 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | NAME := osx-builder 2 | PLATFORM := $(shell go env | grep GOHOSTOS | cut -d '"' -f 2) 3 | ARCH := $(shell go env | grep GOARCH | cut -d '"' -f 2) 4 | BRANCH := $(shell git rev-parse --abbrev-ref HEAD) 5 | VERSION := v1.0.1-nocgo 6 | 7 | build: 8 | go build -ldflags "-X main.Version $(VERSION)" -o build/$(NAME) 9 | 10 | dist: build 11 | @rm -rf dist && mkdir dist 12 | (cd $(shell pwd)/build && tar -cvzf ../dist/$(NAME)_$(VERSION)_$(PLATFORM)_$(ARCH).tar.gz *); \ 13 | (cd $(shell pwd)/dist && shasum -a 512 $(NAME)_$(VERSION)_$(PLATFORM)_$(ARCH).tar.gz > $(NAME)_$(VERSION)_$(PLATFORM)_$(ARCH).tar.gz.sha512); 14 | 15 | deps: 16 | go get github.com/c4milo/github-release 17 | 18 | release: dist 19 | @latest_tag=$$(git describe --tags `git rev-list --tags --max-count=1`); \ 20 | comparison="$$latest_tag..HEAD"; \ 21 | if [ -z "$$latest_tag" ]; then comparison=""; fi; \ 22 | changelog=$$(git log $$comparison --oneline --no-merges --reverse); \ 23 | github-release c4milo/$(NAME) $(VERSION) $(BRANCH) "**Changelog**
$$changelog" 'dist/*'; \ 24 | git pull 25 | 26 | test: 27 | go test ./... 28 | 29 | .PHONY: dist release build test deps 30 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # OS X Builder 2 | 3 | The OS X Builder is a small HTTP API that allows to run Go's buildlets on OS X virtual machines, running on VMWare Fusion. 4 | 5 | 6 | ## How it works 7 | A VMware base image is provided upon VM creation. This image is cached and reused by the API as a "gold" or "pristine" copy. The gold image will be only downloaded and unpacked the first time the API receives a request for creating a virtual machine. From then on, and as long as the gold image is the same, the API is going to re-use that gold image to create linked clones from it. This is what the folder structure kept by this API looks like: 8 | 9 | ![](https://cldup.com/ekbdZPiZtc.png) 10 | 11 | For more information about how linked clones work, please refer to the official documentation: https://www.vmware.com/support/ws55/doc/ws_clone_overview.html 12 | 13 | 14 | ## Caveats 15 | 16 | * VMWare vmrun handles internal locking to avoid corruption of virtual machine files. If there is an attempt to get VM information when the VM is locked, you may get properties with empty values. 17 | 18 | * In case you provide a callback URL, once it is called, there is not guarantee you will receive an IP Address as this will depend on IP acquisition timing as well as VMTools in the Guest OS taking its own time finding out the assigned IP address. 19 | 20 | * When starting a VM in headless mode, the VM doesn't seem to boot in VMWare Fusion 7. 21 | It does boot, though, if we start it with headless mode disabled. Some research was done and it seems to be an issue with VMWare Fusion itself, some Vagrant users have run into the same problem before but the real cause and fix hasn't been determined. 22 | 23 | # API 24 | ## HTTP response codes 25 | 26 | * **202:** Request for creating a virtual machine was accepted 27 | * **500:** Internal error 28 | * **400:** Bad request 29 | * **415:** The provided body data is not an accepted media type (application/json) 30 | * **409:** Conflict when attempting to read virtual machine information. This could be due a stalled lock or a corrupt VMX file. Manual intervention may be needed. 31 | * **404:** Virtual machine was not found 32 | 33 | For errors, along with the HTTP response code, the API will return an error message as well. For example: 34 | 35 | ```json 36 | { 37 | "code": "vm-not-found", 38 | "message": "The requested virtual machine ID was not found" 39 | } 40 | ``` 41 | 42 | ## Create virtual machine 43 | Creates virtual machines asynchronously from an existing VMware virtual machine. 44 | 45 | * **PATH:** `/vms` 46 | * **Method:** `POST` 47 | * **Consumes:** `application/json` 48 | * **Produces:** `application/json` 49 | 50 | **Body** 51 | 52 | ```json 53 | { 54 | "cpus": 2, 55 | "memory": 1024, 56 | "network_type": "nat", 57 | "image": { 58 | "url": "https://github.com/hooklift/boxes/releases/download/coreos-dev-20141126/coreos_developer_vmware.tar.gz", 59 | "checksum": "5cf00d380e28d02f30efaceafef7c7c8bdedae33", 60 | "checksum_type": "sha1" 61 | }, 62 | "headless": true, 63 | "callback_url": "http://foo.com/myscript", 64 | } 65 | ``` 66 | 67 | **Valid network types:** 68 | 69 | * bridged 70 | * nat 71 | * hostonly 72 | 73 | Memory is understood in megabytes. 74 | 75 | 76 | **Valid checksum algorithms:** 77 | 78 | * md5 79 | * sha1 80 | * sha256 81 | * sha512 82 | 83 | **Supported compression formats for image packages:** 84 | 85 | * tar.gz 86 | * tar.bzip2 87 | * zip 88 | * tar 89 | 90 | ### Example 91 | 92 | ```shell 93 | % curl -d@create.json http://localhost:12345/vms 94 | { 95 | "id": "282ee68a-2e4d-4bd7-9c0e-7f37e12fc489", 96 | "image": { 97 | "url": "https://github.com/hooklift/boxes/releases/download/coreos-dev-20141126/coreos_developer_vmware.tar.gz", 98 | "checksum": "5cf00d380e28d02f30efaceafef7c7c8bdedae33", 99 | "checksum_type": "sha1" 100 | }, 101 | "cpus": 2, 102 | "memory": 1024, 103 | "headless": true, 104 | "ip_address": "", 105 | "status": "", 106 | "guest_os": "" 107 | } 108 | ``` 109 | 110 | Upon creation, you can either wait for your callback URL to be called by means of a POST method, or pull the VM information from time to time until you get back the rest of the information. 111 | 112 | Once the creation process finishes, the following properties are going to be populated: 113 | 114 | * ip_address 115 | * status 116 | 117 | 118 | ## Retrieve virtual machine information 119 | * **PATH:** `/vms/:id` 120 | * **Method:** `GET` 121 | * **Produces:** `application/json` 122 | 123 | ### Example 124 | 125 | ```shell 126 | % curl http://localhost:12345/vms/c8a934d72293a7d31baf 127 | { 128 | "id": "c8a934d72293a7d31baf", 129 | "image": { 130 | "url": "https://github.com/hooklift/boxes/releases/download/coreos-dev-20141126/coreos_developer_vmware.tar.gz", 131 | "checksum": "5cf00d380e28d02f30efaceafef7c7c8bdedae33", 132 | "checksum_type": "sha1" 133 | }, 134 | "cpus": 2, 135 | "memory": 1024, 136 | "headless": false, 137 | "ip_address": "192.168.123.147", 138 | "status": "running", 139 | } 140 | ``` 141 | 142 | ## Destroy virtual machine 143 | * **PATH:** `/vms/:id` 144 | * **Method:** `DELETE` 145 | 146 | ### Example 147 | 148 | ```shell 149 | % curl -X DELETE http://localhost:12345/vms/c8a934d72293a7d31baf 150 | ``` 151 | 152 | -------------------------------------------------------------------------------- /apperror/error.go: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, version 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | 5 | package apperror 6 | 7 | import "runtime" 8 | 9 | // Error defines a custom error type for this application. 10 | type Error struct { 11 | Code string `json:"code"` 12 | Message string `json:"message"` 13 | HTTPStatus int `json:"-"` 14 | } 15 | 16 | // Implements Error interface. 17 | func (e *Error) Error() string { 18 | return e.Message 19 | } 20 | 21 | // Utility function to get stack traces just in case they are needed. 22 | func GetStacktrace() string { 23 | trace := make([]byte, 1024) 24 | count := runtime.Stack(trace, false) 25 | return string(trace[:count]) 26 | } 27 | -------------------------------------------------------------------------------- /config/config.go: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, version 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | 5 | package config 6 | 7 | import ( 8 | "os" 9 | "os/user" 10 | "path/filepath" 11 | ) 12 | 13 | var ( 14 | // Port for HTTP service to bind to 15 | Port string 16 | // Where all the virtual machines are going to be created 17 | VMSPath string 18 | // Where all the gold images are going to be cached 19 | GoldImgsPath string 20 | // Where all the raw images are downloaded to 21 | ImagesPath string 22 | ) 23 | 24 | // Initializes service's configuration 25 | func init() { 26 | Port = os.Getenv("PORT") 27 | if Port == "" { 28 | Port = "12345" 29 | } 30 | 31 | usr, err := user.Current() 32 | if err != nil { 33 | panic(err) 34 | } 35 | 36 | basePath := filepath.Join(usr.HomeDir, ".osx-builder") 37 | VMSPath = filepath.Join(basePath, "vms") 38 | GoldImgsPath = filepath.Join(basePath, "gold") 39 | ImagesPath = filepath.Join(basePath, "images") 40 | } 41 | -------------------------------------------------------------------------------- /osx-builder.go: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, version 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | 5 | package main 6 | 7 | import ( 8 | "log" 9 | "net/http" 10 | "strings" 11 | 12 | "github.com/c4milo/osx-builder/config" 13 | "github.com/c4milo/osx-builder/vms" 14 | ) 15 | 16 | // Version string is injected when building the binary from Makefile. 17 | var Version string 18 | 19 | func main() { 20 | // Keeps a registry of path function handlers. 21 | registry := map[string]map[string]func(http.ResponseWriter, *http.Request){ 22 | "/vms": vms.Handlers, 23 | } 24 | 25 | // Main entry point to handle requests. Based on a URL path, this piece of code 26 | // iterates the registry and invokes the path's function handler if there is 27 | // match. 28 | http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { 29 | for p, handlers := range registry { 30 | if strings.HasPrefix(req.URL.Path, p) { 31 | if handlerFn, ok := handlers[req.Method]; ok { 32 | handlerFn(w, req) 33 | return 34 | } 35 | w.WriteHeader(http.StatusMethodNotAllowed) 36 | w.Write([]byte("Method Not Allowed")) 37 | return 38 | } 39 | } 40 | 41 | w.WriteHeader(http.StatusNotFound) 42 | w.Write([]byte("Not Found")) 43 | }) 44 | 45 | address := ":" + config.Port 46 | log.Fatal(http.ListenAndServe(address, nil)) 47 | } 48 | -------------------------------------------------------------------------------- /pkg/render/render.go: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, version 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | 5 | package render 6 | 7 | import ( 8 | "encoding/json" 9 | "fmt" 10 | "net/http" 11 | "strconv" 12 | ) 13 | 14 | // Options represents the set of values to pass when rendering content. 15 | type Options struct { 16 | // HTTP status to return 17 | Status int 18 | // Content to serialize 19 | Data interface{} 20 | // Whether or not to cache the response 21 | Cache bool 22 | } 23 | 24 | // JSON renders JSON content and sends it to the HTTP client. It supports caching. 25 | func JSON(w http.ResponseWriter, opts Options) error { 26 | if &w == nil { 27 | return fmt.Errorf("You must provide a valid http.ResponseWriter") 28 | } 29 | 30 | headers := w.Header() 31 | headers.Set("Content-Type", "application/json; charset=utf-8") 32 | 33 | if opts.Cache { 34 | headers.Set("Cache-Control", "no-cache, no-store, must-revalidate") 35 | headers.Set("Pragma", "no-cache") 36 | headers.Set("Expires", "0") 37 | } 38 | 39 | jsonBytes, err := json.Marshal(opts.Data) 40 | if err != nil { 41 | return err 42 | } 43 | 44 | headers.Set("Content-Length", strconv.Itoa(len(jsonBytes))) 45 | if opts.Status <= 0 { 46 | opts.Status = http.StatusOK 47 | } 48 | w.WriteHeader(opts.Status) 49 | w.Write(jsonBytes) 50 | 51 | return nil 52 | } 53 | -------------------------------------------------------------------------------- /pkg/render/render_test.go: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, version 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | 5 | package render 6 | -------------------------------------------------------------------------------- /pkg/unzipit/fixtures/cfgdrv.iso: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/c4milo/osx-builder/f76983e0b3807a639b99e9887d5dc9d3bf1e2189/pkg/unzipit/fixtures/cfgdrv.iso -------------------------------------------------------------------------------- /pkg/unzipit/fixtures/filetest.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/c4milo/osx-builder/f76983e0b3807a639b99e9887d5dc9d3bf1e2189/pkg/unzipit/fixtures/filetest.zip -------------------------------------------------------------------------------- /pkg/unzipit/fixtures/tar-without-directory-entries.tar.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/c4milo/osx-builder/f76983e0b3807a639b99e9887d5dc9d3bf1e2189/pkg/unzipit/fixtures/tar-without-directory-entries.tar.gz -------------------------------------------------------------------------------- /pkg/unzipit/fixtures/test.tar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/c4milo/osx-builder/f76983e0b3807a639b99e9887d5dc9d3bf1e2189/pkg/unzipit/fixtures/test.tar -------------------------------------------------------------------------------- /pkg/unzipit/fixtures/test.tar.bzip2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/c4milo/osx-builder/f76983e0b3807a639b99e9887d5dc9d3bf1e2189/pkg/unzipit/fixtures/test.tar.bzip2 -------------------------------------------------------------------------------- /pkg/unzipit/fixtures/test.tar.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/c4milo/osx-builder/f76983e0b3807a639b99e9887d5dc9d3bf1e2189/pkg/unzipit/fixtures/test.tar.gz -------------------------------------------------------------------------------- /pkg/unzipit/fixtures/test.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/c4milo/osx-builder/f76983e0b3807a639b99e9887d5dc9d3bf1e2189/pkg/unzipit/fixtures/test.zip -------------------------------------------------------------------------------- /pkg/unzipit/fixtures/test2.tar.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/c4milo/osx-builder/f76983e0b3807a639b99e9887d5dc9d3bf1e2189/pkg/unzipit/fixtures/test2.tar.gz -------------------------------------------------------------------------------- /pkg/unzipit/unzipit.go: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, version 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | 5 | package unzipit 6 | 7 | import ( 8 | "archive/tar" 9 | "archive/zip" 10 | "bufio" 11 | "bytes" 12 | "compress/bzip2" 13 | "compress/gzip" 14 | "errors" 15 | "io" 16 | "io/ioutil" 17 | "os" 18 | "path" 19 | "path/filepath" 20 | "runtime" 21 | "strings" 22 | ) 23 | 24 | var ( 25 | magicZIP = []byte{0x50, 0x4b, 0x03, 0x04} 26 | magicGZ = []byte{0x1f, 0x8b} 27 | magicBZIP = []byte{0x42, 0x5a} 28 | magicTAR = []byte{0x75, 0x73, 0x74, 0x61, 0x72} // at offset 257 29 | ) 30 | 31 | // Check whether a file has the magic number for tar, gzip, bzip2 or zip files 32 | // 33 | // Note that this function does not advance the Reader. 34 | // 35 | // 50 4b 03 04 for pkzip format 36 | // 1f 8b for .gz 37 | // 42 5a for bzip 38 | // 75 73 74 61 72 at offset 257 for tar files 39 | func magicNumber(reader *bufio.Reader, offset int) (string, error) { 40 | headerBytes, err := reader.Peek(offset + 5) 41 | if err != nil { 42 | return "", err 43 | } 44 | 45 | magic := headerBytes[offset : offset+5] 46 | 47 | if bytes.Equal(magicTAR, magic) { 48 | return "tar", nil 49 | } 50 | 51 | if bytes.Equal(magicZIP, magic[0:4]) { 52 | return "zip", nil 53 | } 54 | 55 | if bytes.Equal(magicGZ, magic[0:2]) { 56 | return "gzip", nil 57 | } else if bytes.Equal(magicBZIP, magic[0:2]) { 58 | return "bzip", nil 59 | } 60 | 61 | return "", nil 62 | } 63 | 64 | // Unpack unpacks a compressed and archived file and places result output in destination 65 | // path. 66 | // 67 | // File formats supported are: 68 | // - .tar.gz 69 | // - .tar.bzip2 70 | // - .zip 71 | // - .tar 72 | // 73 | // If it cannot recognize the file format, it will save the file, as is, to the 74 | // destination path. 75 | func Unpack(file *os.File, destPath string) (string, error) { 76 | if file == nil { 77 | return "", errors.New("You must provide a valid file to unpack") 78 | } 79 | 80 | var err error 81 | if destPath == "" { 82 | destPath, err = ioutil.TempDir(os.TempDir(), "unpackit-") 83 | if err != nil { 84 | return "", err 85 | } 86 | } 87 | 88 | // Makes sure despPath exists 89 | os.MkdirAll(destPath, 0740) 90 | 91 | r := bufio.NewReader(file) 92 | return UnpackStream(r, destPath) 93 | } 94 | 95 | // UnpackStream unpacks a compressed stream. Note that if the stream is a using ZIP 96 | // compression (but only ZIP compression), it's going to get buffered in its entirety 97 | // to memory prior to decompression. 98 | func UnpackStream(reader io.Reader, destPath string) (string, error) { 99 | r := bufio.NewReader(reader) 100 | 101 | // Reads magic number from the stream so we can better determine how to proceed 102 | ftype, err := magicNumber(r, 0) 103 | if err != nil { 104 | return "", err 105 | } 106 | 107 | var decompressingReader *bufio.Reader 108 | switch ftype { 109 | case "gzip": 110 | decompressingReader, err = GunzipStream(r) 111 | if err != nil { 112 | return "", err 113 | } 114 | case "bzip": 115 | decompressingReader, err = Bunzip2Stream(r) 116 | if err != nil { 117 | return "", err 118 | } 119 | case "zip": 120 | // Like TAR, ZIP is also an archiving format, therefore we can just return 121 | // after it finishes 122 | return UnzipStream(r, destPath) 123 | default: 124 | decompressingReader = r 125 | } 126 | 127 | // Check magic number in offset 257 too see if this is also a TAR file 128 | ftype, err = magicNumber(decompressingReader, 257) 129 | if ftype == "tar" { 130 | return Untar(decompressingReader, destPath) 131 | } 132 | 133 | // If it's not a TAR archive then save it to disk as is. 134 | destRawFile := filepath.Join(destPath, sanitize(path.Base("tarstream"))) 135 | 136 | // Creates destination file 137 | destFile, err := os.Create(destRawFile) 138 | if err != nil { 139 | return "", err 140 | } 141 | defer destFile.Close() 142 | 143 | // Copies data to destination file 144 | if _, err := io.Copy(destFile, decompressingReader); err != nil { 145 | return "", err 146 | } 147 | 148 | return destPath, nil 149 | } 150 | 151 | // Bunzip2 decompresses a bzip2 file and returns the decompressed stream 152 | func Bunzip2(file *os.File) (*bufio.Reader, error) { 153 | freader := bufio.NewReader(file) 154 | bzip2Reader, err := Bunzip2Stream(freader) 155 | if err != nil { 156 | return nil, err 157 | } 158 | 159 | return bufio.NewReader(bzip2Reader), nil 160 | } 161 | 162 | // Bunzip2Stream unpacks a bzip2 stream 163 | func Bunzip2Stream(reader io.Reader) (*bufio.Reader, error) { 164 | return bufio.NewReader(bzip2.NewReader(reader)), nil 165 | } 166 | 167 | // Gunzip decompresses a gzip file and returns the decompressed stream 168 | func Gunzip(file *os.File) (*bufio.Reader, error) { 169 | freader := bufio.NewReader(file) 170 | gunzipReader, err := GunzipStream(freader) 171 | if err != nil { 172 | return nil, err 173 | } 174 | 175 | return bufio.NewReader(gunzipReader), nil 176 | } 177 | 178 | // GunzipStream unpacks a gzipped stream 179 | func GunzipStream(reader io.Reader) (*bufio.Reader, error) { 180 | var decompressingReader *gzip.Reader 181 | var err error 182 | if decompressingReader, err = gzip.NewReader(reader); err != nil { 183 | return nil, err 184 | } 185 | 186 | return bufio.NewReader(decompressingReader), nil 187 | } 188 | 189 | // Unzip decompresses and unarchives a ZIP archive, returning the final path or an error 190 | func Unzip(file *os.File, destPath string) (string, error) { 191 | fstat, err := file.Stat() 192 | if err != nil { 193 | return "", err 194 | } 195 | 196 | zr, err := zip.NewReader(file, fstat.Size()) 197 | if err != nil { 198 | return "", err 199 | } 200 | 201 | return unpackZip(zr, destPath) 202 | } 203 | 204 | // UnzipStream unpacks a ZIP stream. Because of the nature of the ZIP format, 205 | // the stream is copied to memory before decompression. 206 | func UnzipStream(r io.Reader, destPath string) (string, error) { 207 | data, err := ioutil.ReadAll(r) 208 | if err != nil { 209 | return "", err 210 | } 211 | 212 | memReader := bytes.NewReader(data) 213 | zr, err := zip.NewReader(memReader, int64(len(data))) 214 | if err != nil { 215 | return "", err 216 | } 217 | 218 | return unpackZip(zr, destPath) 219 | } 220 | 221 | func unpackZip(zr *zip.Reader, destPath string) (string, error) { 222 | // Iterate through the files in the archive, 223 | // printing some of their contents. 224 | pathSeparator := string(os.PathSeparator) 225 | for _, f := range zr.File { 226 | rc, err := f.Open() 227 | if err != nil { 228 | return "", err 229 | } 230 | defer rc.Close() 231 | 232 | filePath := sanitize(f.Name) 233 | sepInd := strings.LastIndex(filePath, pathSeparator) 234 | 235 | // If the file is a subdirectory, it creates it before attempting to 236 | // create the actual file 237 | if sepInd > -1 { 238 | directory := filePath[0:sepInd] 239 | os.MkdirAll(filepath.Join(destPath, directory), 0740) 240 | } 241 | 242 | file, err := os.Create(filepath.Join(destPath, filePath)) 243 | if err != nil { 244 | return "", err 245 | } 246 | defer file.Close() 247 | 248 | if _, err := io.CopyN(file, rc, int64(f.UncompressedSize64)); err != nil { 249 | return "", err 250 | } 251 | defer rc.Close() 252 | } 253 | return destPath, nil 254 | } 255 | 256 | // Untar unarchives a TAR archive and returns the final destination path or an error 257 | func Untar(data io.Reader, destPath string) (string, error) { 258 | // Makes sure destPath exists 259 | os.MkdirAll(destPath, 0740) 260 | 261 | tr := tar.NewReader(data) 262 | 263 | // Iterate through the files in the archive. 264 | rootdir := destPath 265 | for { 266 | hdr, err := tr.Next() 267 | if err == io.EOF { 268 | // end of tar archive 269 | break 270 | } 271 | 272 | if err != nil { 273 | return rootdir, err 274 | } 275 | 276 | if hdr.FileInfo().IsDir() { 277 | d := filepath.Join(destPath, sanitize(hdr.Name)) 278 | if rootdir == destPath { 279 | rootdir = d 280 | } 281 | os.MkdirAll(d, os.FileMode(hdr.Mode)) 282 | continue 283 | } 284 | 285 | path := filepath.Join(destPath, sanitize(hdr.Name)) 286 | parentDir, _ := filepath.Split(path) 287 | 288 | err = os.MkdirAll(parentDir, 0740) 289 | if err != nil { 290 | return rootdir, err 291 | } 292 | 293 | file, err := os.Create(path) 294 | if err != nil { 295 | return rootdir, err 296 | } 297 | 298 | defer file.Close() 299 | 300 | if _, err := io.Copy(file, tr); err != nil { 301 | return rootdir, err 302 | } 303 | } 304 | 305 | return rootdir, nil 306 | } 307 | 308 | // Sanitizes name to avoid overwriting sensitive system files when unarchiving 309 | func sanitize(name string) string { 310 | // Gets rid of volume drive label in Windows 311 | if len(name) > 1 && name[1] == ':' && runtime.GOOS == "windows" { 312 | name = name[2:] 313 | } 314 | 315 | name = filepath.Clean(name) 316 | name = filepath.ToSlash(name) 317 | for strings.HasPrefix(name, "../") { 318 | name = name[3:] 319 | } 320 | return name 321 | } 322 | -------------------------------------------------------------------------------- /pkg/unzipit/unzipit_test.go: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, version 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | 5 | package unzipit 6 | 7 | import ( 8 | "archive/tar" 9 | "bufio" 10 | "bytes" 11 | "fmt" 12 | "io/ioutil" 13 | "os" 14 | "path" 15 | "path/filepath" 16 | "reflect" 17 | "runtime" 18 | "testing" 19 | ) 20 | 21 | // assert fails the test if the condition is false. 22 | func assert(tb testing.TB, condition bool, msg string, v ...interface{}) { 23 | if !condition { 24 | _, file, line, _ := runtime.Caller(1) 25 | fmt.Printf("\033[31m%s:%d: "+msg+"\033[39m\n\n", append([]interface{}{filepath.Base(file), line}, v...)...) 26 | tb.FailNow() 27 | } 28 | } 29 | 30 | // ok fails the test if an err is not nil. 31 | func ok(tb testing.TB, err error) { 32 | if err != nil { 33 | _, file, line, _ := runtime.Caller(1) 34 | fmt.Printf("\033[31m%s:%d: unexpected error: %s\033[39m\n\n", filepath.Base(file), line, err.Error()) 35 | tb.FailNow() 36 | } 37 | } 38 | 39 | // equals fails the test if exp is not equal to act. 40 | func equals(tb testing.TB, exp, act interface{}) { 41 | if !reflect.DeepEqual(exp, act) { 42 | _, file, line, _ := runtime.Caller(1) 43 | fmt.Printf("\033[31m%s:%d:\n\n\texp: %#v\n\n\tgot: %#v\033[39m\n\n", filepath.Base(file), line, exp, act) 44 | tb.FailNow() 45 | } 46 | } 47 | 48 | func TestUnpack(t *testing.T) { 49 | var tests = []struct { 50 | filepath string 51 | files int 52 | }{ 53 | {"./fixtures/test.tar.bzip2", 2}, 54 | {"./fixtures/test.tar.gz", 2}, 55 | {"./fixtures/test.zip", 2}, 56 | {"./fixtures/filetest.zip", 3}, 57 | {"./fixtures/test.tar", 2}, 58 | {"./fixtures/cfgdrv.iso", 1}, 59 | {"./fixtures/test2.tar.gz", 4}, 60 | {"./fixtures/tar-without-directory-entries.tar.gz", 1}, 61 | } 62 | 63 | for _, test := range tests { 64 | tempDir, err := ioutil.TempDir(os.TempDir(), "unpackit-tests-"+path.Base(test.filepath)+"-") 65 | ok(t, err) 66 | defer os.RemoveAll(tempDir) 67 | 68 | file, err := os.Open(test.filepath) 69 | ok(t, err) 70 | defer file.Close() 71 | 72 | destPath, err := Unpack(file, tempDir) 73 | ok(t, err) 74 | 75 | length := calcNumberOfFiles(t, destPath) 76 | assert(t, length == test.files, fmt.Sprintf("%d != %d for %s", length, test.files, destPath)) 77 | } 78 | } 79 | 80 | func TestUnpackStream(t *testing.T) { 81 | var tests = []struct { 82 | filepath string 83 | files int 84 | }{ 85 | {"./fixtures/test.tar.bzip2", 2}, 86 | {"./fixtures/test.tar.gz", 2}, 87 | {"./fixtures/test.zip", 2}, 88 | {"./fixtures/test.tar", 2}, 89 | {"./fixtures/cfgdrv.iso", 1}, 90 | {"./fixtures/test2.tar.gz", 4}, 91 | } 92 | 93 | for _, test := range tests { 94 | tempDir, err := ioutil.TempDir(os.TempDir(), "unpackit-tests-"+path.Base(test.filepath)+"-") 95 | ok(t, err) 96 | defer os.RemoveAll(tempDir) 97 | 98 | file, err := os.Open(test.filepath) 99 | ok(t, err) 100 | defer file.Close() 101 | 102 | destPath, err := UnpackStream(bufio.NewReader(file), tempDir) 103 | ok(t, err) 104 | 105 | finfo, err := ioutil.ReadDir(destPath) 106 | ok(t, err) 107 | 108 | length := len(finfo) 109 | assert(t, length == test.files, fmt.Sprintf("%d != %d for %s", length, test.files, destPath)) 110 | } 111 | } 112 | 113 | func TestMagicNumber(t *testing.T) { 114 | var tests = []struct { 115 | filepath string 116 | offset int 117 | ftype string 118 | }{ 119 | {"./fixtures/test.tar.bzip2", 0, "bzip"}, 120 | {"./fixtures/test.tar.gz", 0, "gzip"}, 121 | {"./fixtures/test.zip", 0, "zip"}, 122 | {"./fixtures/test.tar", 257, "tar"}, 123 | } 124 | 125 | for _, test := range tests { 126 | file, err := os.Open(test.filepath) 127 | ok(t, err) 128 | 129 | ftype, err := magicNumber(bufio.NewReader(file), test.offset) 130 | file.Close() 131 | ok(t, err) 132 | 133 | assert(t, ftype == test.ftype, ftype+" != "+test.ftype) 134 | } 135 | } 136 | 137 | func TestUntar(t *testing.T) { 138 | // Create a buffer to write our archive to. 139 | buf := new(bytes.Buffer) 140 | 141 | // Create a new tar archive. 142 | tw := tar.NewWriter(buf) 143 | 144 | // Add some files to the archive. 145 | var files = []struct { 146 | Name, Body string 147 | }{ 148 | {"readme.txt", "This archive contains some text files."}, 149 | {"gopher.txt", "Gopher names:\nGeorge\nGeoffrey\nGonzo"}, 150 | {"todo.txt", "Get animal handling licence."}, 151 | } 152 | for _, file := range files { 153 | hdr := &tar.Header{ 154 | Name: file.Name, 155 | Size: int64(len(file.Body)), 156 | } 157 | err := tw.WriteHeader(hdr) 158 | ok(t, err) 159 | 160 | _, err = tw.Write([]byte(file.Body)) 161 | ok(t, err) 162 | } 163 | 164 | // Make sure to check the error on Close. 165 | err := tw.Close() 166 | ok(t, err) 167 | 168 | // Open the tar archive for reading. 169 | r := bytes.NewReader(buf.Bytes()) 170 | destDir, err := ioutil.TempDir(os.TempDir(), "terraform-vix") 171 | ok(t, err) 172 | defer os.RemoveAll(destDir) 173 | 174 | _, err = Untar(r, destDir) 175 | ok(t, err) 176 | } 177 | 178 | func TestSanitize(t *testing.T) { 179 | var tests = []struct { 180 | malicious string 181 | sanitized string 182 | }{ 183 | {"../../.././etc/passwd", "etc/passwd"}, 184 | {"../../etc/passwd", "etc/passwd"}, 185 | {"./etc/passwd", "etc/passwd"}, 186 | {"./././etc/passwd", "etc/passwd"}, 187 | {"nonexistant/b/../file.txt", "nonexistant/file.txt"}, 188 | {"abc../def", "abc../def"}, 189 | {"a/b/c/../d", "a/b/d"}, 190 | {"a/../../c", "c"}, 191 | {"...../etc/password", "...../etc/password"}, 192 | } 193 | 194 | for _, test := range tests { 195 | a := sanitize(test.malicious) 196 | msg := fmt.Sprintf("%s != %s for malicious string %s", a, test.sanitized, test.malicious) 197 | assert(t, a == test.sanitized, msg) 198 | } 199 | } 200 | 201 | func calcNumberOfFiles(t *testing.T, searchDir string) int { 202 | fileList := []string{} 203 | 204 | err := filepath.Walk(searchDir, func(path string, f os.FileInfo, err error) error { 205 | if !f.IsDir() { 206 | fileList = append(fileList, path) 207 | } 208 | return nil 209 | }) 210 | 211 | if err != nil { 212 | t.FailNow() 213 | } 214 | 215 | return len(fileList) 216 | } 217 | -------------------------------------------------------------------------------- /pkg/vmware/fusion7.go: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, version 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | 5 | package vmware 6 | 7 | import ( 8 | "errors" 9 | "fmt" 10 | "log" 11 | "os" 12 | "os/exec" 13 | "strconv" 14 | "strings" 15 | ) 16 | 17 | // Fusion7VM defines a VMWare Fusion7 provider. 18 | type Fusion7VM struct { 19 | vmxPath string 20 | vmRunPath string 21 | } 22 | 23 | // NewFusion7VM creates a new instance of Fusion7VM, receiving a VMX file path 24 | // as parameter. 25 | func NewFusion7VM(vmxPath string) *Fusion7VM { 26 | fusion7 := &Fusion7VM{ 27 | vmxPath: vmxPath, 28 | } 29 | 30 | if err := fusion7.lookupVMRunPath(); err != nil { 31 | log.Fatalln(err) 32 | } 33 | 34 | return fusion7 35 | } 36 | 37 | // lookupVMRunPath finds vmrun tool in local filesystem. 38 | func (v *Fusion7VM) lookupVMRunPath() error { 39 | vmrunPath := os.Getenv("VMWARE_VMRUN_PATH") 40 | 41 | if vmrunPath == "" { 42 | vmrunPath = "/Applications/VMware Fusion.app/Contents/Library/vmrun" 43 | } 44 | 45 | if _, err := os.Stat(vmrunPath); err != nil { 46 | if os.IsNotExist(err) { 47 | return fmt.Errorf("[Fusion7] VMWare vmrun program not found at path: %s", vmrunPath) 48 | } 49 | } 50 | 51 | v.vmRunPath = vmrunPath 52 | return nil 53 | } 54 | 55 | // verifyVMXPath verifies that the VMX file path is not empty. 56 | func (v *Fusion7VM) verifyVMXPath() error { 57 | if v.vmxPath == "" { 58 | return errors.New("[Fusion7] Empty VMX file path. Nothing to operate on.") 59 | } 60 | return nil 61 | } 62 | 63 | // CloneFrom clones the source VMX file into the VMX file path of the function receiver. 64 | func (v *Fusion7VM) CloneFrom(src string, ctype CloneType) error { 65 | if err := v.verifyVMXPath(); err != nil { 66 | return err 67 | } 68 | 69 | cmd := exec.Command(v.vmRunPath, "clone", src, v.vmxPath, string(ctype)) 70 | if _, _, err := runAndLog(cmd); err != nil { 71 | return err 72 | } 73 | 74 | return nil 75 | } 76 | 77 | // Info returns the virtual machine information from VMWare 78 | func (v *Fusion7VM) Info() (*VMInfo, error) { 79 | if err := v.verifyVMXPath(); err != nil { 80 | return nil, err 81 | } 82 | 83 | vmx, err := readVMXFile(v.vmxPath) 84 | if err != nil { 85 | return nil, err 86 | } 87 | 88 | info := new(VMInfo) 89 | info.Name = vmx["displayname"] 90 | info.Annotation = vmx["annotation"] 91 | 92 | numcpus, err := strconv.ParseInt(vmx["numvcpus"], 0, 0) 93 | if err != nil { 94 | return nil, err 95 | } 96 | 97 | memsize, err := strconv.ParseInt(vmx["memsize"], 0, 0) 98 | if err != nil { 99 | return nil, err 100 | } 101 | 102 | info.CPUs = int(numcpus) 103 | info.MemorySize = int(memsize) 104 | info.NetworkType = NetworkType(vmx["ethernet0.connectiontype"]) 105 | info.GuestOS = vmx["guestos"] 106 | 107 | return info, nil 108 | } 109 | 110 | // SetInfo stores the VM information in VMWare 111 | func (v *Fusion7VM) SetInfo(info *VMInfo) error { 112 | if err := v.verifyVMXPath(); err != nil { 113 | return err 114 | } 115 | 116 | vmx, err := readVMXFile(v.vmxPath) 117 | if err != nil { 118 | return err 119 | } 120 | 121 | vmx["displayname"] = info.Name 122 | vmx["annotation"] = info.Annotation 123 | vmx["numvcpus"] = strconv.Itoa(info.CPUs) 124 | vmx["memsize"] = strconv.Itoa(info.MemorySize) 125 | 126 | // This is to make sure to auto answer popups windows in the GUI. This is 127 | // especially helpful when running in headless mode 128 | vmx["msg.autoanswer"] = "true" 129 | 130 | // The following settings does nothing in Fusion7. 131 | // vmx["gui.exitatpoweroff"] = "true" 132 | // vmx["gui.restricted"] = "true" 133 | // vmx["gui.exitonclihlt"] = "true" 134 | 135 | // Deletes all network adapters. For the simplicity's sake 136 | // we are going to deliberately use only one network adapter. 137 | for k, _ := range vmx { 138 | if strings.HasPrefix(k, "ethernet") { 139 | delete(vmx, k) 140 | } 141 | } 142 | 143 | vmx["ethernet0.present"] = "true" 144 | vmx["ethernet0.startconnected"] = "true" 145 | vmx["ethernet0.virtualdev"] = "e1000" 146 | vmx["ethernet0.connectiontype"] = string(info.NetworkType) 147 | 148 | if err := writeVMXFile(v.vmxPath, vmx); err != nil { 149 | return err 150 | } 151 | 152 | return nil 153 | } 154 | 155 | // Start launches a virtual machine. 156 | // 157 | // Known issues: 158 | // When starting a VM in headless mode, the VM doesn't seem to boot in VMWare Fusion 7 159 | // It does boot, though, if we start it with headless mode disabled. Go figure why... 160 | // The problem with starting with headless mode disabled is that it won't be possible to delete 161 | // the VM using normal means and to overcome this we are deleting the VM from 162 | // the filesystem by force. 163 | func (v *Fusion7VM) Start(headless bool) error { 164 | if err := v.verifyVMXPath(); err != nil { 165 | return err 166 | } 167 | 168 | guiParam := "gui" 169 | if headless { 170 | guiParam = "nogui" 171 | } 172 | 173 | cmd := exec.Command(v.vmRunPath, "start", v.vmxPath, guiParam) 174 | if _, _, err := runAndLog(cmd); err != nil { 175 | return err 176 | } 177 | 178 | return nil 179 | } 180 | 181 | // Stop stops a virtual machine. 182 | func (v *Fusion7VM) Stop() error { 183 | if err := v.verifyVMXPath(); err != nil { 184 | return err 185 | } 186 | 187 | cmd := exec.Command(v.vmRunPath, "stop", v.vmxPath) 188 | if _, _, err := runAndLog(cmd); err != nil { 189 | return err 190 | } 191 | 192 | return nil 193 | } 194 | 195 | // Delete removes a virtual machine using normal vmrun means. 196 | func (v *Fusion7VM) Delete() error { 197 | if err := v.verifyVMXPath(); err != nil { 198 | return err 199 | } 200 | 201 | cmd := exec.Command(v.vmRunPath, "deleteVM", v.vmxPath) 202 | if _, _, err := runAndLog(cmd); err != nil { 203 | return err 204 | } 205 | 206 | return nil 207 | } 208 | 209 | // IsRunning returns whether or not a virtual machine is running. 210 | func (v *Fusion7VM) IsRunning() (bool, error) { 211 | if err := v.verifyVMXPath(); err != nil { 212 | return false, err 213 | } 214 | 215 | cmd := exec.Command(v.vmRunPath, "list") 216 | stdout, _, err := runAndLog(cmd) 217 | if err != nil { 218 | return false, err 219 | } 220 | 221 | for _, line := range strings.Split(stdout, "\n") { 222 | if line == v.vmxPath { 223 | return true, nil 224 | } 225 | } 226 | 227 | return false, nil 228 | } 229 | 230 | // HasToolsInstalled returns whether or not VMWare Tools is running in the VM. 231 | func (v *Fusion7VM) HasToolsInstalled() (bool, error) { 232 | if err := v.verifyVMXPath(); err != nil { 233 | return false, err 234 | } 235 | 236 | cmd := exec.Command(v.vmRunPath, "checkToolsState", v.vmxPath) 237 | stdout, _, err := runAndLog(cmd) 238 | if err != nil { 239 | return false, err 240 | } 241 | 242 | for _, line := range strings.Split(stdout, "\n") { 243 | if line == "installed" { 244 | return true, nil 245 | } 246 | } 247 | return false, nil 248 | } 249 | 250 | // IPAddress queries VMWare Tools to get the virtual machine IP address. 251 | func (v *Fusion7VM) IPAddress() (string, error) { 252 | if err := v.verifyVMXPath(); err != nil { 253 | return "", err 254 | } 255 | 256 | cmd := exec.Command(v.vmRunPath, "getGuestIPAddress", v.vmxPath) 257 | stdout, _, err := runAndLog(cmd) 258 | if err != nil { 259 | return "", err 260 | } 261 | 262 | addresses := strings.Split(stdout, "\n") 263 | 264 | if len(addresses) > 0 { 265 | return addresses[0], nil 266 | } 267 | 268 | return "", nil 269 | } 270 | 271 | // Exists returns whether or not the VMX file for this VM exists. 272 | func (v *Fusion7VM) Exists() (bool, error) { 273 | if err := v.verifyVMXPath(); err != nil { 274 | return false, err 275 | } 276 | 277 | if _, err := os.Stat(v.vmxPath); os.IsNotExist(err) { 278 | return false, nil 279 | } else if err != nil { 280 | return false, err 281 | } 282 | 283 | return true, nil 284 | } 285 | -------------------------------------------------------------------------------- /pkg/vmware/vmware.go: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, version 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | 5 | package vmware 6 | 7 | import ( 8 | "bytes" 9 | "fmt" 10 | "log" 11 | "os/exec" 12 | "strings" 13 | ) 14 | 15 | // NetworkType represents all valid types of networking in VMware, except by "custom". 16 | type NetworkType string 17 | 18 | const ( 19 | NetworkHostOnly NetworkType = "hostonly" 20 | NetworkNAT NetworkType = "nat" 21 | NetworkBridged NetworkType = "bridged" 22 | ) 23 | 24 | // CloneType represents the type of clonning strategy when creating new VMs. 25 | type CloneType string 26 | 27 | const ( 28 | CloneFull CloneType = "full" 29 | CloneLinked CloneType = "linked" 30 | ) 31 | 32 | // VMInfo defines the minimum amount of VM properties needed either to be configured 33 | // or to be returned back for the purpose of this project. 34 | type VMInfo struct { 35 | Name string 36 | Annotation string 37 | MemorySize int 38 | CPUs int 39 | GuestOS string 40 | NetworkType NetworkType 41 | } 42 | 43 | // VirtualMachine defines the set of virtual machine operations used in this project. 44 | type VirtualMachine interface { 45 | lookupVMRunPath() error 46 | Info() (*VMInfo, error) 47 | SetInfo(info *VMInfo) error 48 | CloneFrom(srcfile string, ctype CloneType) error 49 | Start(headless bool) error 50 | Stop() error 51 | Delete() error 52 | IsRunning() (bool, error) 53 | HasToolsInstalled() (bool, error) 54 | IPAddress() (string, error) 55 | Exists() (bool, error) 56 | } 57 | 58 | // Borrowed from https://github.com/mitchellh/packer/blob/master/builder/vmware/common/driver.go 59 | func runAndLog(cmd *exec.Cmd) (string, string, error) { 60 | var stdout, stderr bytes.Buffer 61 | 62 | log.Printf("[VMWare] Executing: %s %v", cmd.Path, cmd.Args[1:]) 63 | cmd.Stdout = &stdout 64 | cmd.Stderr = &stderr 65 | err := cmd.Run() 66 | 67 | stdoutString := strings.TrimSpace(stdout.String()) 68 | stderrString := strings.TrimSpace(stderr.String()) 69 | 70 | if _, ok := err.(*exec.ExitError); ok { 71 | message := stderrString 72 | if message == "" { 73 | message = stdoutString 74 | } 75 | 76 | err = fmt.Errorf("[VMWare] error: %s", message) 77 | } 78 | 79 | log.Printf("stdout: %s", stdoutString) 80 | log.Printf("stderr: %s", stderrString) 81 | 82 | // Replace these for Windows, we only want to deal with Unix 83 | // style line endings. 84 | returnStdout := strings.Replace(stdout.String(), "\r\n", "\n", -1) 85 | returnStderr := strings.Replace(stderr.String(), "\r\n", "\n", -1) 86 | 87 | return returnStdout, returnStderr, err 88 | } 89 | -------------------------------------------------------------------------------- /pkg/vmware/vmx.go: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, version 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | 5 | package vmware 6 | 7 | import ( 8 | "bytes" 9 | "io" 10 | "io/ioutil" 11 | "os" 12 | "sort" 13 | "strings" 14 | ) 15 | 16 | // readVMX reads data from the given VMX file path. 17 | func readVMXFile(vmxpath string) (map[string]string, error) { 18 | data, err := ioutil.ReadFile(vmxpath) 19 | if err != nil { 20 | return nil, err 21 | } 22 | 23 | vmx := make(map[string]string) 24 | for _, line := range strings.Split(string(data), "\n") { 25 | values := strings.Split(line, "=") 26 | if len(values) != 2 { 27 | continue 28 | } 29 | 30 | k := strings.TrimSpace(values[0]) 31 | v := strings.TrimSpace(values[1]) 32 | vmx[strings.ToLower(k)] = strings.Trim(v, `"`) 33 | } 34 | 35 | return vmx, nil 36 | } 37 | 38 | // writeVMX writes to the provided VMX file path from data provided in a map. 39 | func writeVMXFile(vmxpath string, vmx map[string]string) error { 40 | f, err := os.Create(vmxpath) 41 | if err != nil { 42 | return err 43 | } 44 | 45 | defer f.Close() 46 | 47 | i := 0 48 | keys := make([]string, len(vmx)) 49 | for k := range vmx { 50 | keys[i] = k 51 | i++ 52 | } 53 | 54 | sort.Strings(keys) 55 | 56 | var buf bytes.Buffer 57 | for _, key := range keys { 58 | buf.WriteString(key + " = " + `"` + vmx[key] + `"`) 59 | buf.WriteString("\n") 60 | } 61 | 62 | if _, err = io.Copy(f, &buf); err != nil { 63 | return err 64 | } 65 | 66 | return nil 67 | } 68 | -------------------------------------------------------------------------------- /vms/assert_test.go: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, version 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | 5 | package vms 6 | 7 | import ( 8 | "fmt" 9 | "io/ioutil" 10 | "path/filepath" 11 | "reflect" 12 | "runtime" 13 | "testing" 14 | 15 | log "github.com/Sirupsen/logrus" 16 | ) 17 | 18 | func init() { 19 | log.SetOutput(ioutil.Discard) 20 | log.SetLevel(log.DebugLevel) 21 | } 22 | 23 | // assert fails the test if the condition is false. 24 | func assert(tb testing.TB, condition bool, msg string, v ...interface{}) { 25 | if !condition { 26 | _, file, line, _ := runtime.Caller(1) 27 | fmt.Printf("\033[31m%s:%d: "+msg+"\033[39m\n\n", append([]interface{}{filepath.Base(file), line}, v...)...) 28 | tb.FailNow() 29 | } 30 | } 31 | 32 | // ok fails the test if an err is not nil. 33 | func ok(tb testing.TB, err error) { 34 | if err != nil { 35 | _, file, line, _ := runtime.Caller(1) 36 | fmt.Printf("\033[31m%s:%d: unexpected error: %s\033[39m\n\n", filepath.Base(file), line, err.Error()) 37 | tb.FailNow() 38 | } 39 | } 40 | 41 | // equals fails the test if exp is not equal to act. 42 | func equals(tb testing.TB, exp, act interface{}) { 43 | if !reflect.DeepEqual(exp, act) { 44 | _, file, line, _ := runtime.Caller(1) 45 | fmt.Printf("\033[31m%s:%d:\n\n\texp: %#v\n\n\tgot: %#v\033[39m\n\n", filepath.Base(file), line, exp, act) 46 | tb.FailNow() 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /vms/error.go: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, version 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | 5 | package vms 6 | 7 | import ( 8 | "net/http" 9 | 10 | "github.com/c4milo/osx-builder/apperror" 11 | ) 12 | 13 | var ErrInternal = apperror.Error{ 14 | Code: "internal-error", 15 | Message: "Whops! Our team is currently looking into this. Apologies for the inconvenience", 16 | HTTPStatus: http.StatusInternalServerError, 17 | } 18 | 19 | var ErrVMNotFound = apperror.Error{ 20 | Code: "vm-not-found", 21 | Message: "The requested virtual machine ID was not found", 22 | HTTPStatus: http.StatusNotFound, 23 | } 24 | 25 | var ErrReadingReqBody = apperror.Error{ 26 | Code: "request-io-error", 27 | Message: "There was an IO error while reading request's body. Please try again.", 28 | HTTPStatus: http.StatusBadRequest, 29 | } 30 | 31 | var ErrParsingJSON = apperror.Error{ 32 | Code: "invalid-json", 33 | Message: "There was an error parsing the provided JSON message. Please try again.", 34 | HTTPStatus: http.StatusUnsupportedMediaType, 35 | } 36 | 37 | var ErrCreatingVM = apperror.Error{ 38 | Code: "vm-create-error", 39 | Message: "There was an unexpected error trying to create the virtual machine. We are looking into it.", 40 | HTTPStatus: http.StatusInternalServerError, 41 | } 42 | 43 | var ErrOpeningVM = apperror.Error{ 44 | Code: "vm-open-error", 45 | Message: "The VM was found but we were unable to open its configuration file. " + 46 | "Caused, most likely, by a corrupt VMX file or a stalled lock.", 47 | HTTPStatus: http.StatusConflict, 48 | } 49 | 50 | var ErrCbURL = apperror.Error{ 51 | Code: "err-marshalling-response", 52 | Message: "There was an error marshaling the response. Please try again creating your virtual machine.", 53 | } 54 | -------------------------------------------------------------------------------- /vms/fixtures/test.box: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/c4milo/osx-builder/f76983e0b3807a639b99e9887d5dc9d3bf1e2189/vms/fixtures/test.box -------------------------------------------------------------------------------- /vms/image.go: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, version 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | 5 | package vms 6 | 7 | import ( 8 | "crypto/md5" 9 | "crypto/sha1" 10 | "crypto/sha256" 11 | "crypto/sha512" 12 | "crypto/tls" 13 | "errors" 14 | "fmt" 15 | "hash" 16 | "io" 17 | "log" 18 | "net/http" 19 | "net/url" 20 | "os" 21 | "path" 22 | "path/filepath" 23 | ) 24 | 25 | // A virtual machine image definition. 26 | type Image struct { 27 | // Image URL where to download from 28 | URL string `json:"url"` 29 | // Checksum of the image, used to check integrity after downloading it 30 | Checksum string `json:"checksum"` 31 | // Algorithm use to check the checksum 32 | ChecksumType string `json:"checksum_type"` 33 | // Password to decrypt the virtual machine if it is encrypted. This is used by 34 | // VIX to be able to open the virtual machine 35 | Password string `json:"-"` 36 | // Internal file reference 37 | file *os.File 38 | } 39 | 40 | // Downloads and a virtual machine image. 41 | func (img *Image) Download(destPath string) error { 42 | if img.URL == "" { 43 | return errors.New("Image URL is required") 44 | } 45 | 46 | if img.Checksum == "" { 47 | return errors.New("Image checksum is required") 48 | } 49 | 50 | if img.ChecksumType == "" { 51 | return errors.New("Image checksum type is required") 52 | } 53 | 54 | if destPath == "" { 55 | destPath = os.TempDir() 56 | } 57 | 58 | u, err := url.Parse(img.URL) 59 | if err != nil { 60 | return err 61 | } 62 | 63 | _, filename := path.Split(u.Path) 64 | if filename == "" { 65 | filename = "unnamed" 66 | } 67 | 68 | os.MkdirAll(destPath, 0740) 69 | 70 | filePath := filepath.Join(destPath, filename) 71 | 72 | fetchAndWrite := func() error { 73 | data, err := img.fetch(img.URL) 74 | if err != nil { 75 | return err 76 | } 77 | 78 | img.file, err = img.write(data, filePath) 79 | if err != nil { 80 | return err 81 | } 82 | data.Close() 83 | 84 | return nil 85 | } 86 | 87 | log.Printf("[DEBUG] Opening %s...", filePath) 88 | img.file, err = os.Open(filePath) 89 | if err != nil { 90 | log.Printf("[DEBUG] %s file does not exist. Downloading it...", filename) 91 | 92 | if err = fetchAndWrite(); err != nil { 93 | return err 94 | } 95 | } 96 | 97 | if err = img.verify(); err != nil { 98 | log.Printf("[DEBUG] File on disk does not match current checksum.\n Downloading file again...") 99 | 100 | if err = fetchAndWrite(); err != nil { 101 | return err 102 | } 103 | 104 | if err = img.verify(); err != nil { 105 | return err 106 | } 107 | } 108 | 109 | return nil 110 | } 111 | 112 | // Gets a VM image through HTTP. 113 | func (img *Image) fetch(URL string) (io.ReadCloser, error) { 114 | client := &http.Client{ 115 | Transport: &http.Transport{ 116 | TLSClientConfig: &tls.Config{ 117 | InsecureSkipVerify: false, 118 | }, 119 | }, 120 | } 121 | 122 | resp, err := client.Get(URL) 123 | if err != nil { 124 | return nil, err 125 | } 126 | 127 | if resp.StatusCode != 200 { 128 | return nil, fmt.Errorf("Unable to fetch data, server returned code %d", resp.StatusCode) 129 | } 130 | 131 | return resp.Body, nil 132 | 133 | } 134 | 135 | // Writes the downloading stream down to a file. 136 | func (img *Image) write(reader io.Reader, filePath string) (*os.File, error) { 137 | log.Printf("[DEBUG] Downloading file data to %s", filePath) 138 | 139 | compressedFile, err := os.Create(filePath) 140 | if err != nil { 141 | return nil, err 142 | } 143 | 144 | written, err := io.Copy(compressedFile, reader) 145 | if err != nil { 146 | return nil, err 147 | } 148 | log.Printf("[DEBUG] %d bytes written to %s", written, filePath) 149 | 150 | return compressedFile, nil 151 | } 152 | 153 | // Verifies the image package integrity after it is downloaded. 154 | func (img *Image) verify() error { 155 | // Makes sure the file cursor is positioned at the beginning of the file 156 | _, err := img.file.Seek(0, 0) 157 | if err != nil { 158 | return err 159 | } 160 | 161 | log.Printf("[DEBUG] Verifying image checksum...") 162 | var hasher hash.Hash 163 | 164 | switch img.ChecksumType { 165 | case "md5": 166 | hasher = md5.New() 167 | case "sha1": 168 | hasher = sha1.New() 169 | case "sha256": 170 | hasher = sha256.New() 171 | case "sha512": 172 | hasher = sha512.New() 173 | default: 174 | return fmt.Errorf("[ERROR] Crypto algorithm no supported: %s", img.ChecksumType) 175 | } 176 | _, err = io.Copy(hasher, img.file) 177 | if err != nil { 178 | return err 179 | } 180 | 181 | result := fmt.Sprintf("%x", hasher.Sum(nil)) 182 | 183 | if result != img.Checksum { 184 | return fmt.Errorf("[ERROR] Checksum does not match\n Result: %s\n Expected: %s", result, img.Checksum) 185 | } 186 | 187 | return nil 188 | } 189 | -------------------------------------------------------------------------------- /vms/image_test.go: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, version 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | 5 | package vms 6 | 7 | import ( 8 | "fmt" 9 | "io" 10 | "io/ioutil" 11 | "net/http" 12 | "net/http/httptest" 13 | "os" 14 | 15 | "testing" 16 | ) 17 | 18 | func TestDownload(t *testing.T) { 19 | ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 20 | w.Header().Set("Content-Type", "application/x-tar") 21 | w.Header().Set("Content-Encoding", "x-gzip") 22 | 23 | file, err := os.Open("./fixtures/test.box") 24 | ok(t, err) 25 | assert(t, file != nil, "Failed loading fixture file") 26 | defer file.Close() 27 | 28 | io.Copy(w, file) 29 | })) 30 | defer ts.Close() 31 | 32 | image := Image{ 33 | URL: ts.URL, 34 | Checksum: "35fd19dc1bb7e18a365c1c589df2292942c197a4", 35 | ChecksumType: "sha1", 36 | } 37 | 38 | destDir, err := ioutil.TempDir(os.TempDir(), "terraform-vix") 39 | ok(t, err) 40 | defer os.RemoveAll(destDir) 41 | 42 | err = image.Download(destDir) 43 | ok(t, err) 44 | 45 | filename := image.file.Name() 46 | assert(t, filename != "", fmt.Sprintf("%v == %v", filename, nil)) 47 | finfo, err := image.file.Stat() 48 | ok(t, err) 49 | 50 | size := finfo.Size() 51 | assert(t, size > 0, fmt.Sprintf("Image file is empty: %d", size)) 52 | } 53 | -------------------------------------------------------------------------------- /vms/vm.go: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, version 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | 5 | package vms 6 | 7 | import ( 8 | "encoding/base64" 9 | "encoding/json" 10 | "fmt" 11 | "io/ioutil" 12 | "log" 13 | "os" 14 | "path/filepath" 15 | "runtime/debug" 16 | 17 | "github.com/c4milo/osx-builder/config" 18 | "github.com/c4milo/osx-builder/pkg/unzipit" 19 | "github.com/c4milo/osx-builder/pkg/vmware" 20 | ) 21 | 22 | // VMConfig defines all the configurable properties of a virtual machine. 23 | type VMConfig struct { 24 | // ID of the virtual machine 25 | ID string `json:"id"` 26 | // Image to use during the creation of this virtual machine 27 | OSImage Image `json:"image"` 28 | // Number of virtual cpus 29 | CPUs int `json:"cpus"` 30 | // Memory size in megabytes. 31 | Memory int `json:"memory"` 32 | // Network adapters 33 | Network vmware.NetworkType `json:"network_type"` 34 | // Whether to launch the VM with graphical environment 35 | Headless bool `json:"headless"` 36 | } 37 | 38 | // VM defines the properties of a virtual machine. 39 | type VM struct { 40 | VMConfig 41 | // Underlined VMWare virtual machine 42 | vmwareVM vmware.VirtualMachine 43 | // VM IP address as reported by VMWare 44 | IPAddress string `json:"ip_address"` 45 | // Power status 46 | Status string `json:"status"` 47 | } 48 | 49 | // NewVM creates a new instance of VM. 50 | func NewVM(c VMConfig) *VM { 51 | vmxfile := filepath.Join(config.VMSPath, c.ID, c.ID+".vmx") 52 | 53 | return &VM{ 54 | VMConfig: c, 55 | vmwareVM: vmware.NewFusion7VM(vmxfile), 56 | } 57 | } 58 | 59 | // setDefaults assigns defalt values for some VM properties. 60 | func (v *VM) setDefaults() { 61 | if v.CPUs <= 0 { 62 | v.CPUs = 2 63 | } 64 | 65 | if v.Memory < 512 { 66 | v.Memory = 512 67 | } 68 | } 69 | 70 | // unpackGoldImage fetches and decompresses the Gold OS image. 71 | func (v *VM) unpackGoldImage() (string, error) { 72 | image := v.OSImage 73 | goldPath := filepath.Join(config.GoldImgsPath, image.Checksum) 74 | 75 | _, err := os.Stat(goldPath) 76 | finfo, _ := ioutil.ReadDir(goldPath) 77 | goldPathEmpty := len(finfo) == 0 78 | 79 | if os.IsNotExist(err) || goldPathEmpty { 80 | log.Println("[DEBUG] Gold virtual machine does not exist or is empty") 81 | 82 | imgPath := filepath.Join(config.ImagesPath, image.Checksum) 83 | if err = image.Download(imgPath); err != nil { 84 | return "", err 85 | } 86 | defer image.file.Close() 87 | 88 | // Makes sure file cursor is in the right position. 89 | _, err := image.file.Seek(0, 0) 90 | if err != nil { 91 | return "", err 92 | } 93 | 94 | log.Printf("[DEBUG] Unpacking gold virtual machine into %s\n", goldPath) 95 | _, err = unzipit.Unpack(image.file, goldPath) 96 | if err != nil { 97 | debug.PrintStack() 98 | log.Printf("[ERROR] Unpacking gold image %s\n", image.file.Name()) 99 | return "", err 100 | } 101 | } 102 | 103 | return goldPath, nil 104 | } 105 | 106 | // Create creates and launches a virtual machine. 107 | func (v *VM) Create() error { 108 | log.Printf("[DEBUG] Creating VM %s", v.ID) 109 | 110 | goldPath, err := v.unpackGoldImage() 111 | if err != nil { 112 | return err 113 | } 114 | 115 | pattern := filepath.Join(goldPath, "**.vmx") 116 | 117 | log.Printf("[DEBUG] Finding gold vmx file in %s", pattern) 118 | files, _ := filepath.Glob(pattern) 119 | 120 | if len(files) == 0 { 121 | return fmt.Errorf("[ERROR] Gold vmx file was not found: %s", pattern) 122 | } 123 | 124 | goldvmx := files[0] 125 | log.Printf("[DEBUG] Gold vmx file found at %v", goldvmx) 126 | 127 | vmexists, err := v.vmwareVM.Exists() 128 | if err != nil { 129 | return err 130 | } 131 | 132 | if !vmexists { 133 | err := v.vmwareVM.CloneFrom(goldvmx, vmware.CloneLinked) 134 | if err != nil { 135 | return err 136 | } 137 | } 138 | 139 | if err = v.Update(); err != nil { 140 | return err 141 | } 142 | 143 | return nil 144 | } 145 | 146 | // Updates a virtual machine. 147 | func (v *VM) Update() error { 148 | v.setDefaults() 149 | 150 | running, err := v.vmwareVM.IsRunning() 151 | if err != nil { 152 | return err 153 | } 154 | 155 | if running { 156 | log.Printf("[INFO] Virtual machine seems to be running, we need to " + 157 | "power it off in order to make changes.") 158 | err = v.vmwareVM.Stop() 159 | if err != nil { 160 | return err 161 | } 162 | } 163 | 164 | info := &vmware.VMInfo{ 165 | //hacky way of making sure it is a multiple of 4 megabytes 166 | MemorySize: (v.Memory + 3) & ^0x03, 167 | CPUs: v.CPUs, 168 | Name: v.ID, 169 | } 170 | 171 | imageJSON, err := json.Marshal(v.OSImage) 172 | if err != nil { 173 | return err 174 | } 175 | 176 | // Encodes JSON data as Base64 so that the VMX file is not 177 | // interpreted by VMWare as corrupted. 178 | info.Annotation = base64.StdEncoding.EncodeToString(imageJSON) 179 | 180 | log.Printf("[DEBUG] Adding network adapter...") 181 | info.NetworkType = v.Network 182 | 183 | err = v.vmwareVM.SetInfo(info) 184 | if err != nil { 185 | return err 186 | } 187 | 188 | log.Println("[INFO] Powering virtual machine on...") 189 | err = v.vmwareVM.Start(v.Headless) 190 | if err != nil { 191 | return err 192 | } 193 | 194 | return nil 195 | } 196 | 197 | // Destroy removes a virtual machine. 198 | func (v *VM) Destroy() error { 199 | running, err := v.vmwareVM.IsRunning() 200 | if err != nil { 201 | return err 202 | } 203 | 204 | if running { 205 | log.Printf("[DEBUG] Stopping %s...", v.ID) 206 | if err = v.vmwareVM.Stop(); err != nil { 207 | return err 208 | } 209 | log.Printf("[DEBUG] %s stopped", v.ID) 210 | } 211 | 212 | // We are not handling errors here on purpose and due to vmrun limitations 213 | v.vmwareVM.Delete() 214 | 215 | if v.ID != "" { 216 | os.RemoveAll(filepath.Join(config.VMSPath, v.ID)) 217 | } 218 | 219 | return nil 220 | } 221 | 222 | // FindVM finds a virtual machine by ID. 223 | func FindVM(id string) (*VM, error) { 224 | vm := NewVM(VMConfig{ 225 | ID: id, 226 | }) 227 | 228 | exists, err := vm.vmwareVM.Exists() 229 | if err != nil { 230 | return nil, err 231 | } 232 | 233 | if !exists { 234 | return nil, nil 235 | } 236 | 237 | err = vm.Refresh() 238 | if err != nil { 239 | return nil, err 240 | } 241 | 242 | return vm, nil 243 | } 244 | 245 | // Refresh synchronizes VM state against VMware. 246 | func (v *VM) Refresh() error { 247 | log.Printf("[DEBUG] Refreshing state with VMWare...") 248 | info, err := v.vmwareVM.Info() 249 | if err != nil { 250 | return err 251 | } 252 | 253 | v.CPUs = info.CPUs 254 | v.Memory = info.MemorySize 255 | v.ID = info.Name 256 | 257 | v.IPAddress, _ = v.vmwareVM.IPAddress() 258 | 259 | imageJSONBase64 := info.Annotation 260 | imageJSON, err := base64.StdEncoding.DecodeString(imageJSONBase64) 261 | if err != nil { 262 | return err 263 | } 264 | 265 | var image Image 266 | err = json.Unmarshal(imageJSON, &image) 267 | if err != nil { 268 | return err 269 | } 270 | v.OSImage = image 271 | v.Network = info.NetworkType 272 | 273 | running, err := v.vmwareVM.IsRunning() 274 | if err != nil { 275 | return err 276 | } 277 | 278 | if running { 279 | v.Status = "running" 280 | } else { 281 | v.Status = "stopped" 282 | } 283 | 284 | log.Printf("[DEBUG] Finished refreshing state from VMWare") 285 | return nil 286 | } 287 | -------------------------------------------------------------------------------- /vms/web.go: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, version 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | 5 | package vms 6 | 7 | import ( 8 | "bytes" 9 | "crypto/rand" 10 | "encoding/json" 11 | "fmt" 12 | "io/ioutil" 13 | "log" 14 | "net/http" 15 | "path" 16 | 17 | "github.com/c4milo/osx-builder/apperror" 18 | "github.com/c4milo/osx-builder/pkg/render" 19 | ) 20 | 21 | // Handlers is a map to functions where each function is in charge of handling 22 | // a HTTP verb or method. 23 | var Handlers map[string]func(http.ResponseWriter, *http.Request) = map[string]func(http.ResponseWriter, *http.Request){ 24 | "POST": CreateVM, 25 | "GET": GetVM, 26 | "DELETE": DestroyVM, 27 | } 28 | 29 | // CreateVMParams defines parameters supported by the CreateVM service. 30 | type CreateVMParams struct { 31 | VMConfig 32 | // Script to run inside the Guest OS upon first boot 33 | BootstrapScript string `json:"bootstrap_script"` 34 | // Callback URL to post results once the VM creation process finishes. It 35 | // must support POST requests and be ready to receive JSON in the body of 36 | // the request. 37 | CallbackURL string `json:"callback_url"` 38 | } 39 | 40 | // sendResult invokes callback URL with results of the creation process only if a 41 | // callback URL was provided. 42 | func sendResult(url string, value interface{}) { 43 | if url == "" { 44 | return 45 | } 46 | data, err := json.Marshal(value) 47 | if err != nil { 48 | log.Printf(`[ERROR] msg="%s" value=%+v code=%s error="%s" stacktrace=%s\n`, 49 | ErrCbURL.Message, value, ErrCbURL.Code, err.Error(), apperror.GetStacktrace()) 50 | 51 | data, err = json.Marshal(ErrCbURL) 52 | if err != nil { 53 | return 54 | } 55 | } 56 | _, err = http.Post(url, "application/json", bytes.NewBuffer(data)) 57 | if err != nil { 58 | log.Printf(`[ERROR] msg="%s" value=%+v code=%s error="%s" stacktrace=%s\n`, 59 | ErrCbURL.Message, value, ErrCbURL.Code, err.Error(), apperror.GetStacktrace()) 60 | } 61 | } 62 | 63 | // CreateVM creates a virtual machine using the given parameters. 64 | func CreateVM(w http.ResponseWriter, req *http.Request) { 65 | var params CreateVMParams 66 | body, err := ioutil.ReadAll(req.Body) 67 | 68 | if err != nil { 69 | log.Printf(`[ERROR] msg="%s" code=%s error="%s" stacktrace=%s\n`, 70 | ErrReadingReqBody.Message, ErrReadingReqBody.Code, err.Error(), apperror.GetStacktrace()) 71 | 72 | render.JSON(w, render.Options{ 73 | Status: ErrReadingReqBody.HTTPStatus, 74 | Data: ErrReadingReqBody, 75 | }) 76 | return 77 | } 78 | 79 | err = json.Unmarshal(body, ¶ms) 80 | if err != nil { 81 | log.Printf(`[ERROR] msg="%s" code=%s error="%s" stacktrace=%s\n`, 82 | ErrParsingJSON.Message, ErrParsingJSON.Code, err.Error(), apperror.GetStacktrace()) 83 | 84 | render.JSON(w, render.Options{ 85 | Status: ErrParsingJSON.HTTPStatus, 86 | Data: ErrParsingJSON, 87 | }) 88 | return 89 | } 90 | 91 | b := make([]byte, 10) 92 | _, err = rand.Read(b) 93 | if err != nil { 94 | log.Printf(`[ERROR] msg="%s" code=%s error="%s" stacktrace=%s\n`, 95 | ErrInternal.Message, ErrInternal.Code, err.Error(), apperror.GetStacktrace()) 96 | 97 | render.JSON(w, render.Options{ 98 | Status: ErrInternal.HTTPStatus, 99 | Data: ErrInternal, 100 | }) 101 | return 102 | } 103 | 104 | id := fmt.Sprintf("%x", b) 105 | params.VMConfig.ID = id 106 | 107 | vm := NewVM(params.VMConfig) 108 | 109 | go func() { 110 | err := vm.Create() 111 | if err != nil { 112 | log.Printf(`[ERROR] msg="%s" value=%+v code=%s error="%s" stacktrace=%s\n`, 113 | ErrCreatingVM.Message, vm, ErrCreatingVM.Code, err.Error(), apperror.GetStacktrace()) 114 | 115 | sendResult(params.CallbackURL, ErrCreatingVM) 116 | return 117 | } 118 | 119 | // One last effort to get an IP... 120 | if vm.IPAddress == "" { 121 | vm.Refresh() 122 | } 123 | 124 | sendResult(params.CallbackURL, vm) 125 | }() 126 | 127 | render.JSON(w, render.Options{ 128 | Status: http.StatusAccepted, 129 | Data: vm, 130 | }) 131 | } 132 | 133 | // DestroyVMParams defines parameters supported by the DestroyVM service. 134 | type DestroyVMParams struct { 135 | // Virtual machine ID 136 | ID string 137 | } 138 | 139 | // DestroyVM removes virtual machines by its ID. 140 | func DestroyVM(w http.ResponseWriter, req *http.Request) { 141 | params := DestroyVMParams{ 142 | ID: path.Base(req.URL.Path), 143 | } 144 | 145 | vm, err := FindVM(params.ID) 146 | if err != nil { 147 | log.Printf(`[ERROR] msg="%s" code=%s error="%s" stacktrace=%s\n`, 148 | ErrOpeningVM.Message, ErrOpeningVM.Code, err.Error(), apperror.GetStacktrace()) 149 | 150 | render.JSON(w, render.Options{ 151 | Status: ErrOpeningVM.HTTPStatus, 152 | Data: ErrOpeningVM, 153 | }) 154 | return 155 | } 156 | 157 | if vm == nil { 158 | log.Printf(`[ERROR] msg="%s" code=%s\n`, 159 | ErrVMNotFound.Message, ErrOpeningVM.Code) 160 | 161 | render.JSON(w, render.Options{ 162 | Status: ErrVMNotFound.HTTPStatus, 163 | Data: ErrVMNotFound, 164 | }) 165 | return 166 | } 167 | 168 | err = vm.Destroy() 169 | if err != nil { 170 | log.Printf(`[ERROR] msg="%s" code=%s error="%s" stacktrace=%s\n`, 171 | ErrInternal.Message, ErrInternal.Code, err.Error(), apperror.GetStacktrace()) 172 | 173 | render.JSON(w, render.Options{ 174 | Status: ErrInternal.HTTPStatus, 175 | Data: ErrInternal, 176 | }) 177 | return 178 | } 179 | 180 | render.JSON(w, render.Options{ 181 | Status: http.StatusNoContent, 182 | }) 183 | } 184 | 185 | // GetVMParams defines parameters supported by the GetVM service. 186 | type GetVMParams struct { 187 | ID string 188 | } 189 | 190 | // GetVM returns information of a virtual machine given its ID. 191 | func GetVM(w http.ResponseWriter, req *http.Request) { 192 | params := GetVMParams{ 193 | ID: path.Base(req.URL.Path), 194 | } 195 | 196 | vm, err := FindVM(params.ID) 197 | if err != nil { 198 | log.Printf(`[ERROR] msg="%s" code=%s error="%s" stacktrace=%s\n`, 199 | ErrOpeningVM.Message, ErrOpeningVM.Code, err.Error(), apperror.GetStacktrace()) 200 | 201 | render.JSON(w, render.Options{ 202 | Status: ErrOpeningVM.HTTPStatus, 203 | Data: ErrOpeningVM, 204 | }) 205 | return 206 | } 207 | 208 | if vm == nil { 209 | log.Printf(`[ERROR] msg="%s" code=%s\n`, 210 | ErrVMNotFound.Message, ErrOpeningVM.Code) 211 | 212 | render.JSON(w, render.Options{ 213 | Status: ErrVMNotFound.HTTPStatus, 214 | Data: ErrVMNotFound, 215 | }) 216 | return 217 | } 218 | 219 | render.JSON(w, render.Options{ 220 | Status: http.StatusOK, 221 | Data: vm, 222 | }) 223 | } 224 | --------------------------------------------------------------------------------