From b84fceba8ec773a09a32eed88c2d974689497064 Mon Sep 17 00:00:00 2001 From: Adam Leff Date: Mon, 17 Aug 2015 14:43:43 -0400 Subject: [PATCH] complete refactor with tests and rubocop --- .rubocop.yml | 14 + CHANGELOG.md | 17 +- LICENSE.txt | 193 ++++- README.md | 314 ++++---- examples/VIDEOS.md | 57 ++ examples/httpd-cookbook/.kitchen.vcair.yml | 26 - examples/windows_customization.bat | 53 ++ kitchen-vcair.gemspec | 27 +- lib/kitchen/driver/vcair.rb | 615 +++++++-------- lib/kitchen/driver/vcair_version.rb | 10 +- spec/spec_helper.rb | 17 + spec/vcair_spec.rb | 825 +++++++++++++++++++++ using-vcair-test-kitchen-driver.mkd | 92 --- 13 files changed, 1583 insertions(+), 677 deletions(-) create mode 100644 .rubocop.yml create mode 100644 examples/VIDEOS.md delete mode 100644 examples/httpd-cookbook/.kitchen.vcair.yml create mode 100644 examples/windows_customization.bat create mode 100644 spec/spec_helper.rb create mode 100644 spec/vcair_spec.rb delete mode 100644 using-vcair-test-kitchen-driver.mkd diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 0000000..91258ec --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,14 @@ +Metrics/AbcSize: + Max: 50 +Metrics/ClassLength: + Max: 300 +Metrics/LineLength: + Max: 130 +Metrics/MethodLength: + Max: 25 +Style/Documentation: + Enabled: false +Style/SignalException: + Enabled: false +Style/SpaceInsideBrackets: + Enabled: false diff --git a/CHANGELOG.md b/CHANGELOG.md index b661574..535ec20 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,13 +1,16 @@ -# 0.1.1 / 2015-06-04 +# kitchen-vcair Changelog + +## Release: 1.0.0 / 2015-08-21 +* Initial public release +* Refactor by Chef Partner Engineering to match style of other VMware plugins +* Support for vCloud Air OnDemand + +## Release: 0.1.1 / 2015-06-04 * Destroy working * Password updates * Documentation updates * Cleanup and refactoring -# 0.1.0 / 2015-05-xx - -* Initial release! Woo! +## Release: 0.1.0 / 2015-05-xx -[@hh]: https://github.com/hh -[@taylor]: https://github.com/taylor -[@vulk]: https://github.com/vulk +* Initial release by Vulk. diff --git a/LICENSE.txt b/LICENSE.txt index d08c02f..5e0fd33 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,13 +1,198 @@ -Authors:: Chris McClimans () -Authors:: Taylor Carpenter () +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ -Copyright (c) 2015 Vulk +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, +and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by +the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all +other entities that control, are controlled by, or are under common +control with that entity. For the purposes of this definition, +"control" means (i) the power, direct or indirect, to cause the +direction or management of such entity, whether by contract or +otherwise, or (ii) ownership of fifty percent (50%) or more of the +outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity +exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, +including but not limited to software source code, documentation +source, and configuration files. + +"Object" form shall mean any form resulting from mechanical +transformation or translation of a Source form, including but +not limited to compiled object code, generated documentation, +and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or +Object form, made available under the License, as indicated by a +copyright notice that is included in or attached to the work +(an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object +form, that is based on (or derived from) the Work and for which the +editorial revisions, annotations, elaborations, or other modifications +represent, as a whole, an original work of authorship. For the purposes +of this License, Derivative Works shall not include works that remain +separable from, or merely link (or bind by name) to the interfaces of, +the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including +the original version of the Work and any modifications or additions +to that Work or Derivative Works thereof, that is intentionally +submitted to Licensor for inclusion in the Work by the copyright owner +or by an individual or Legal Entity authorized to submit on behalf of +the copyright owner. For the purposes of this definition, "submitted" +means any form of electronic, verbal, or written communication sent +to the Licensor or its representatives, including but not limited to +communication on electronic mailing lists, source code control systems, +and issue tracking systems that are managed by, or on behalf of, the +Licensor for the purpose of discussing and improving the Work, but +excluding communication that is conspicuously marked or otherwise +designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity +on behalf of whom a Contribution has been received by Licensor and +subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of +this License, each Contributor hereby grants to You a perpetual, +worldwide, non-exclusive, no-charge, royalty-free, irrevocable +copyright license to reproduce, prepare Derivative Works of, +publicly display, publicly perform, sublicense, and distribute the +Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of +this License, each Contributor hereby grants to You a perpetual, +worldwide, non-exclusive, no-charge, royalty-free, irrevocable +(except as stated in this section) patent license to make, have made, +use, offer to sell, sell, import, and otherwise transfer the Work, +where such license applies only to those patent claims licensable +by such Contributor that are necessarily infringed by their +Contribution(s) alone or by combination of their Contribution(s) +with the Work to which such Contribution(s) was submitted. If You +institute patent litigation against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that the Work +or a Contribution incorporated within the Work constitutes direct +or contributory patent infringement, then any patent licenses +granted to You under this License for that Work shall terminate +as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the +Work or Derivative Works thereof in any medium, with or without +modifications, and in Source or Object form, provided that You +meet the following conditions: + +(a) You must give any other recipients of the Work or +Derivative Works a copy of this License; and + +(b) You must cause any modified files to carry prominent notices +stating that You changed the files; and + +(c) You must retain, in the Source form of any Derivative Works +that You distribute, all copyright, patent, trademark, and +attribution notices from the Source form of the Work, +excluding those notices that do not pertain to any part of +the Derivative Works; and + +(d) If the Work includes a "NOTICE" text file as part of its +distribution, then any Derivative Works that You distribute must +include a readable copy of the attribution notices contained +within such NOTICE file, excluding those notices that do not +pertain to any part of the Derivative Works, in at least one +of the following places: within a NOTICE text file distributed +as part of the Derivative Works; within the Source form or +documentation, if provided along with the Derivative Works; or, +within a display generated by the Derivative Works, if and +wherever such third-party notices normally appear. The contents +of the NOTICE file are for informational purposes only and +do not modify the License. You may add Your own attribution +notices within Derivative Works that You distribute, alongside +or as an addendum to the NOTICE text from the Work, provided +that such additional attribution notices cannot be construed +as modifying the License. + +You may add Your own copyright statement to Your modifications and +may provide additional or different license terms and conditions +for use, reproduction, or distribution of Your modifications, or +for any such Derivative Works as a whole, provided Your use, +reproduction, and distribution of the Work otherwise complies with +the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, +any Contribution intentionally submitted for inclusion in the Work +by You to the Licensor shall be under the terms and conditions of +this License, without any additional terms or conditions. +Notwithstanding the above, nothing herein shall supersede or modify +the terms of any separate license agreement you may have executed +with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade +names, trademarks, service marks, or product names of the Licensor, +except as required for reasonable and customary use in describing the +origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or +agreed to in writing, Licensor provides the Work (and each +Contributor provides its Contributions) on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +implied, including, without limitation, any warranties or conditions +of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A +PARTICULAR PURPOSE. You are solely responsible for determining the +appropriateness of using or redistributing the Work and assume any +risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, +whether in tort (including negligence), contract, or otherwise, +unless required by applicable law (such as deliberate and grossly +negligent acts) or agreed to in writing, shall any Contributor be +liable to You for damages, including any direct, indirect, special, +incidental, or consequential damages of any character arising as a +result of this License or out of the use or inability to use the +Work (including but not limited to damages for loss of goodwill, +work stoppage, computer failure or malfunction, or any and all +other commercial damages or losses), even if such Contributor +has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing +the Work or Derivative Works thereof, You may choose to offer, +and charge a fee for, acceptance of support, warranty, indemnity, +or other liability obligations and/or rights consistent with this +License. However, in accepting such obligations, You may act only +on Your own behalf and on Your sole responsibility, not on behalf +of any other Contributor, and only if You agree to indemnify, +defend, and hold each Contributor harmless for any liability +incurred by, or claims asserted against, such Contributor by reason +of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +To apply the Apache License to your work, attach the following +boilerplate notice, with the fields enclosed by brackets "{}" +replaced with your own identifying information. (Don't include +the brackets!) The text should be enclosed in the appropriate +comment syntax for the file format. We also recommend that a +file or class name and description of purpose be included on the +same "printed page" as the copyright notice for easier +identification within third-party archives. + +Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 +http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, diff --git a/README.md b/README.md index 54bfdfb..3ce0422 100644 --- a/README.md +++ b/README.md @@ -1,17 +1,14 @@ -Kitchen::Vcair -================== +# kitchen-vcair -A vCloud Air Servers driver for Test Kitchen! +A driver to allow Test Kitchen to consume vCloud Air resources to perform testing. -Originally based on the [Rackspace driver](https://github.com/test-kitchen/kitchen-rackspace) (from [Jonathan Hartman's](https://github.com/RoboticCheese)) - - -Installation ------------- +## Installation Add this line to your application's Gemfile: - gem 'kitchen-vcair' +```ruby +gem 'kitchen-vcair' +``` And then execute: @@ -21,216 +18,171 @@ Or install it yourself as: $ gem install kitchen-vcair -Usage ------ +Or even better, install it via ChefDK: -Provide, at a minimum, the required driver options in your `.kitchen.yml` file: + $ chef gem install kitchen-vcair - driver: - name: vcair - vcair_username: [Your vCloud Air username] - vcair_password: [Your vCloud Air password] - vcair_api_host: [Your vCloud Air API Host] - vcair_vm_password: [Initial system password used for bootstrap] - vcair_org: [Your vCloud Air Organization ID] - require_chef_omnibus: [e.g. 'true' or a version number if you need Chef] - platforms: - - name: [A PLATFORM NAME, e.g. 'centos-6'] +## Usage + +After installing the gem as described above, edit your .kitchen.yml file to set the driver to 'vcair' and supply your login credentials: + +```yaml +driver: + name: vcair + vcair_username: user@domain.com + vcair_password: MyS33kretPassword + vcair_api_host: some-host.vchs.vmware.com + vcair_org: M12345678-4321 +``` -By default, the driver will spawn a 1GB server on the base image for your -specified platform. Additional, optional overrides can be provided: +Additionally, the following parameters are required: - image_id: [SERVER IMAGE ID] - vcair_net: [ROUTED_NETWORK_WITH_ACCESS_TO_CHEF_SERVER] - flavor_id: [SERVER FLAVOR ID] - server_name: [A FRIENDLY SERVER NAME] - public_key_path: [PATH TO YOUR PUBLIC SSH KEY] - wait_for: [NUM OF SECONDS TO WAIT BEFORE TIMING OUT, DEFAULT 600] - no_ssh_tcp_check: [DEFAULTS TO false, SKIPS TCP CHECK WHEN true] - no_ssh_tcp_check_sleep: [NUM OF SECONDS TO SLEEP IF no_ssh_tcp_check IS SET] + * **vdc_id** or **vdc_name**: The ID or name of the vDC in which to create your vApp/VM. + * **catalog_id** or **catalog_name**: The ID or name of the catalog that contains your image/template. + * **image_id** or **image_name**: The ID or name of the image you wish to use to create your VM. + * **network_id** or **network_name**: The ID or name of the network to which to attach to your VM. -If targeting windows, be sure to add ```transport``` and ```verifier`` options: +There are a number of optional parameters you can configure as well: - transport: - name: winrm - connection_retries: 15 - connection_retry_sleep: 15 - max_wait_until_ready: 600 - username: 'administrator' - password: 'Password1' - verifier: - name: pester + * **cpus**: The number of vCPUs to configure for your VM. Default: 1 + * **memory**: The amount of RAM, in MB, to configure for your VM. Default: 1024 + * **vcair_api_path**: The URI path for the compute API. This needs to be set when using vCloud Air OnDemand. Default: /api + * **vm_password**: The password to set via VM customization for the root/administrator user. + * Be sure to set the same password in your `transport` section, too! + * NOTE: see the *known issues* section below regarding Windows and passwords. -You also have the option of providing some configs via environment variables: +All of the above settings can be set globally (in the top-level `driver` section), or can be set individually for each platform. For example, you may wish to set your vDC and network globally, but set your catalog and image for each individual platform, and increase the vCPUs/RAM assigned to your windows node: - export VCAIR_API_HOST='API_HOST.vchs.vmware.com' - export VCAIR_VM_PASSWORD='SOME_INITIAL_PASSWORD' - export VCAIR_ORG='MNNNNNNNNN-NNNN' - export VCAIR_USERNAME='YOUR_USERNAME' - export VCAIR_PASSWORD='YOUR_PASSWORD' +```yaml +driver: + name: vcair + vcair_username: user@domain.com + vcair_password: MyS33kretPassword + vcair_api_host: some-host.vchs.vmware.com + vcair_org: M12345678-4321 + vdc_name: MyCompany VDC 1 + network_name: vdc1-default-routed -Execution: +platforms: + - name: centos + driver: + catalog_name: Public Catalog + image_name: CentOS64-64BIT + - name: windows + driver: + catalog_name: Public Catalog + image_name: W2K12-STD-R2-64BIT + cpus: 2 + memory: 4096 +``` - KITCHEN_YAML=.kitchen.vcair.yml kitchen test +### vCloud Air Subscription vs. OnDemand -Known Issues / Work Arounds ---------------------------- +kitchen-vcair works as-is with vCloud Air Subscription. In vCloud Air OnDemand, +the API path is different. To use this plugin with vCloud Air OnDemand, you +will need to set the `vcair_api_path` configuration parameter to `/api/compute/api`: -##### ssh authentication happens via password only and public_key auth isn't available +```yaml +driver: + vcair_api_path: /api/compute/api +``` -You must populate :vcair_vm_password in your kitchen.yml +Also, in our testing, we found many of the VMware-provided images are missing +core configurations, such as properly-configured DNS resolvers. We strongly +recommend building your own images off the VMware-provided images with proper +configurations. -##### vCloud Air VMs default to an isolated network +## Known Issues and Workarounds -You must populate :vcair_net _OR_ create a non-isolated network (it will use the first available) +### SSH Authentication - passwords vs. public-key -##### SSH access to nodes requires default firewall policy open port 22 +vCloud Air does not natively support deploying SSH keys to new VMs like other +cloud providers. Therefore, many of the images in the vCloud Air public catalog +only support password authentication. -You may find it easier to use a provisioning node within the same network you nodes will be provisioned on +#### Setting your own password -##### Windows images do not turn on winrm by default +Through VM customization, vCloud Air allows you to specify a password that should +be set for the root account. You can use the `vm_password` config parameter to +specify that password: -##### Windows images force login via rdp console requiring a password change +```yaml +driver: + vm_password: mysupersecretpassword +``` -Both of these can be worked around by including a ```:customization_script``` that sets the password manually, removes the expiry, opens the firewall for and enables winrm. +... and then tell the transport to use that same password: ```yaml -platforms: - - name: win2012-chef12 - driver_config: - image_id: W2K12-STD-64BIT - size: 2gb - customization_script: 'install-winrm-vcair.bat' +transport: + password: mysupersecretpassword ``` -```bat -@echo off +#### Using the pre-generated password by vCloud Air -@rem First Boot... -if “%1%” == “precustomization” ( +**This is not supported.** Unfortunately, a bug in Fog prevents us from +retrieving that password, and a issue/PR will be logged to address this. -echo Do precustomization tasks -@rem during this boot the hostname is set, which requires a reboot +### WinRM Authentication -@rem we also enable winrm over http, plaintext, long timeout, more memory etc +#### Setup -cmd.exe /c winrm quickconfig -q -cmd.exe /c winrm quickconfig -transport:http -cmd.exe /c winrm set winrm/config @{MaxTimeoutms="1800000"} -cmd.exe /c winrm set winrm/config/winrs @{MaxMemoryPerShellMB="300"} -cmd.exe /c winrm set winrm/config/service @{AllowUnencrypted="true"} -cmd.exe /c winrm set winrm/config/service/auth @{Basic="true"} -cmd.exe /c winrm set winrm/config/client/auth @{Basic="true"} -cmd.exe /c winrm set winrm/config/listener?Address=*+Transport=HTTP @{Port="5985"} +Many of the images in the vCloud Air public catalog do not have WinRM enabled. +You will need to provide a customization script to enable WinRM. An example +can be found in the `examples/` directory in this repo. Note that multiple +reboots are required for the VM to become ready for Test Kitchen to use, so +the time required for a Windows VM to be ready is fairly long. -@rem Make sure winrm is off for this boot, but enabled on next -@rem as we don't want a tcp connection available until we are -@rem past postcustomization +A potential workaround to this would be to create your own VM with WinRM enabled +and configured properly and publish it in your own catalog. -cmd.exe /c net stop winrm -cmd.exe /c sc config winrm start= auto +#### Setting your own password -@rem make sure the default on password age is unlimited -@rem this ensures we don't have a password change forced on us -cmd.exe /c net accounts /maxpwage:unlimited +The same customization function that works for Linux does not appear to work for +Windows in vCloud Air. Additionally, Windows does not appear to honor the +customization setting that disables the forced password change on first login. -@rem write out a timestamp for this first boot / customization completes -echo %DATE% %TIME% > C:\vm-is-customized +Therefore, a customization script will need to be used to set your Administrator +password. See the `examples/` directory for a sample customization script that +enables WinRM and sets the Administrator password. -) else if “%1%” == “postcustomization” ( +### NAT and Public IP Support -@rem Second Boot / start winrm, just incase, and fix firewall +Unlike other cloud providers, vCloud Air does not treat public IPs as objects +that can be associated with VMs. Instead, those IPs are associated with network +objects called "gateways" which then require NAT and firewall rules to be +created. The Fog library does not support the creation of those objects. -cmd.exe /c net start winrm -cmd.exe /c netsh advfirewall firewall set rule group="remote administration" new enable=yes -cmd.exe /c netsh firewall add portopening TCP 5985 "Port 5985 for WinRM" +Therefore, only routed networks are supported, and it is required that Test +Kitchen be executed on a network within vCloud Air that has access to the +destination network on which your test VMs will be deployed. -@rem Password Setting and Autologin currently seem broken -@rem when done via the API, so we MUST set it in the postcustomization phase -cmd.exe /c net user administrator Password1 +## License and Authors -@rem in some environments we found the need to specify a DNS address -@rem cmd.exe /c netsh interface ipv4 add dnsserver "Ethernet" address=8.8.8.8 -@rem cmd.exe /c netsh interface ipv4 add dnsserver "Ethernet0" address=8.8.8.8 +Author:: Chef Partner Engineering () -@rem this is our 'ready' boot, password and winrm should be up -echo %DATE% %TIME% > C:\vm-is-ready +Copyright:: Copyright (c) 2015 Chef Software, Inc. -) +License:: Apache License, Version 2.0 + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the License at + +``` +http://www.apache.org/licenses/LICENSE-2.0 ``` -Feature Requests ----------------- - -##### Non CentOS64-64BIT image support - -CentoOS64-64BIT is the only image that allowed setting the password -CentOS and Ubuntu failed to set the password correctly - -##### NAT support - -Only routed networks supported for now - -Walkthru of kitchen-vcair for linux guests ------------------------------------------- - -* [github.com/vulk/kitchen-vcair](https://www.youtube.com/watch?v=5srDko69XJ0&t=03) -* [vchs.vmware.com](https://www.youtube.com/watch?v=5srDko69XJ0&t=15) -* [Walkthrough steps for cloning, building gem](https://www.youtube.com/watch?v=5srDko69XJ0&t=30) -* [git clone git@github.com:/vulk/kitchen-vcair.git](https://www.youtube.com/watch?v=5srDko69XJ0&t=68) -* [cd kitchen-vcair](https://www.youtube.com/watch?v=5srDko69XJ0&t=94) -* [gem build kitchen-vcair.gemspec](https://www.youtube.com/watch?v=5srDko69XJ0&t=100) -* [gem install ./kitchen-vcair-0.1.0.gem](https://www.youtube.com/watch?v=5srDko69XJ0&t=120) -* [quick look through code ](https://www.youtube.com/watch?v=5srDko69XJ0&t=126) -* [git clone git@github.com:chef-cookbooks/httpd.git ](https://www.youtube.com/watch?v=5srDko69XJ0&t=173) -* [walkthrough of .kitchen.vcair.yml](https://www.youtube.com/watch?v=5srDko69XJ0&t=199) -* [walkthrough of environment variables](https://www.youtube.com/watch?v=5srDko69XJ0&t=247) -* [kitchen test](https://www.youtube.com/watch?v=5srDko69XJ0&t=282) -* [vchs.vmware.com virtualmachine list, showing creation of helloworldtest VM](https://www.youtube.com/watch?v=5srDko69XJ0&t=296) -* [knife vcair server list showing creation of helloworld test VM](https://www.youtube.com/watch?v=5srDko69XJ0&t=326) -* [instance provisionied, waiting for ssh](https://www.youtube.com/watch?v=5srDko69XJ0&t=355) -* [ssh available, installing chef-client](https://www.youtube.com/watch?v=5srDko69XJ0&t=400) -* [chef-client starting](https://www.youtube.com/watch?v=5srDko69XJ0&t=499) -* [chef-client finished, apache install completed](https://www.youtube.com/watch?v=5srDko69XJ0&t=515) -* [Kitchen Setup and Verify](https://www.youtube.com/watch?v=5srDko69XJ0&t=516) -* [Kitichen Destroy](https://www.youtube.com/watch?v=5srDko69XJ0&t=517) -* [Kitchen is finished](https://www.youtube.com/watch?v=5srDko69XJ0&t=525) -* [vchs.vmware.com and knife vcair shows vm destroyed](https://www.youtube.com/watch?v=5srDko69XJ0&t=530) - - -Walkthru of kitchen-vcair for windows guests ------------------------------------------- - -* [vmwair-vcair.env.example](https://www.youtube.com/watch?v=k8OZII4UGZs&t=09) -* [.kitchen.vcair.yml](https://www.youtube.com/watch?v=k8OZII4UGZs&t=20) -* [.yml / platforms:customization_script note](https://www.youtube.com/watch?v=k8OZII4UGZs&t=30) -* [customization_script install-winrm-vcair.bat](https://www.youtube.com/watch?v=k8OZII4UGZs&t=37) -* [git clone opscode-cookbooks/iis](https://www.youtube.com/watch?v=k8OZII4UGZs&t=54) -* [start coping files into iis cookbooks](https://www.youtube.com/watch?v=k8OZII4UGZs&t=60) -* [Add kitchen-vcair and kitchen-pester to the Gemfile](https://www.youtube.com/watch?v=k8OZII4UGZs&t=98) -* [bundle install kitchen vcair and pester](https://www.youtube.com/watch?v=k8OZII4UGZs&t=120) -* [KITCHEN_YAML=.kitchen.vcair.yml bundle exec kitchen verify](https://www.youtube.com/watch?v=k8OZII4UGZs&t=150) -* [Server is allocated.](https://www.youtube.com/watch?v=k8OZII4UGZs&t=270) -* ['pre'/'post' customization script ](https://www.youtube.com/watch?v=k8OZII4UGZs&t=300) -* ['pre' customization reboot ](https://www.youtube.com/watch?v=k8OZII4UGZs&t=412) -* ['post' customization boot ](https://www.youtube.com/watch?v=k8OZII4UGZs&t=440) -* [winrm is online](https://www.youtube.com/watch?v=k8OZII4UGZs&t=555) -* [installing chef omnibus](https://www.youtube.com/watch?v=k8OZII4UGZs&t=560) -* [chef-client starts](https://www.youtube.com/watch?v=k8OZII4UGZs&t=600) -* [iis:default recipe runs](https://www.youtube.com/watch?v=k8OZII4UGZs&t=630) -* [verification via kitche-pester](https://www.youtube.com/watch?v=k8OZII4UGZs&t=647) -* [kitchen verify complete!](https://www.youtube.com/watch?v=k8OZII4UGZs&t=660) -* [iis default web page via links](https://www.youtube.com/watch?v=k8OZII4UGZs&t=695) -* [kitchen verify again](https://www.youtube.com/watch?v=k8OZII4UGZs&t=710) -* [kitchen destroy](https://www.youtube.com/watch?v=k8OZII4UGZs&t=735) - -Contributing ------------- - -1. Fork it -2. `bundle install` -3. Create your feature branch (`git checkout -b my-new-feature`) -4. `bundle exec rake` must pass -5. Commit your changes (`git commit -am 'Add some feature'`) -6. Push to the branch (`git push origin my-new-feature`) -7. Create new Pull Request +Unless required by applicable law or agreed to in writing, software distributed under the +License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, +either express or implied. See the License for the specific language governing permissions +and limitations under the License. + +## Contributing + +We'd love to hear from you if this doesn't perform in the manner you expect. Please log a GitHub issue, or even better, submit a Pull Request with a fix! + +1. Fork it ( https://github.com/chef-partners/kitchen-vcair/fork ) +2. Create your feature branch (`git checkout -b my-new-feature`) +3. Commit your changes (`git commit -am 'Add some feature'`) +4. Push to the branch (`git push origin my-new-feature`) +5. Create a new Pull Request diff --git a/examples/VIDEOS.md b/examples/VIDEOS.md new file mode 100644 index 0000000..41801fe --- /dev/null +++ b/examples/VIDEOS.md @@ -0,0 +1,57 @@ +# kitchen-vcair demonstration videos + +Below are videos created by the original plugin author that demonstrate +kitchen-vcair and how to use it. Some configuration parameters have changed +since the initial development of this plugin to keep is consistent with other +VMware-based plugins, so be sure to check the README.md in this repo for the +latest instructions. + +## Linux + +* [github.com/vulk/kitchen-vcair](https://www.youtube.com/watch?v=5srDko69XJ0&t=03) +* [vchs.vmware.com](https://www.youtube.com/watch?v=5srDko69XJ0&t=15) +* [Walkthrough steps for cloning, building gem](https://www.youtube.com/watch?v=5srDko69XJ0&t=30) +* [git clone git@github.com:/vulk/kitchen-vcair.git](https://www.youtube.com/watch?v=5srDko69XJ0&t=68) +* [cd kitchen-vcair](https://www.youtube.com/watch?v=5srDko69XJ0&t=94) +* [gem build kitchen-vcair.gemspec](https://www.youtube.com/watch?v=5srDko69XJ0&t=100) +* [gem install ./kitchen-vcair-0.1.0.gem](https://www.youtube.com/watch?v=5srDko69XJ0&t=120) +* [quick look through code ](https://www.youtube.com/watch?v=5srDko69XJ0&t=126) +* [git clone git@github.com:chef-cookbooks/httpd.git ](https://www.youtube.com/watch?v=5srDko69XJ0&t=173) +* [walkthrough of .kitchen.vcair.yml](https://www.youtube.com/watch?v=5srDko69XJ0&t=199) +* [walkthrough of environment variables](https://www.youtube.com/watch?v=5srDko69XJ0&t=247) +* [kitchen test](https://www.youtube.com/watch?v=5srDko69XJ0&t=282) +* [vchs.vmware.com virtualmachine list, showing creation of helloworldtest VM](https://www.youtube.com/watch?v=5srDko69XJ0&t=296) +* [knife vcair server list showing creation of helloworld test VM](https://www.youtube.com/watch?v=5srDko69XJ0&t=326) +* [instance provisionied, waiting for ssh](https://www.youtube.com/watch?v=5srDko69XJ0&t=355) +* [ssh available, installing chef-client](https://www.youtube.com/watch?v=5srDko69XJ0&t=400) +* [chef-client starting](https://www.youtube.com/watch?v=5srDko69XJ0&t=499) +* [chef-client finished, apache install completed](https://www.youtube.com/watch?v=5srDko69XJ0&t=515) +* [Kitchen Setup and Verify](https://www.youtube.com/watch?v=5srDko69XJ0&t=516) +* [Kitichen Destroy](https://www.youtube.com/watch?v=5srDko69XJ0&t=517) +* [Kitchen is finished](https://www.youtube.com/watch?v=5srDko69XJ0&t=525) +* [vchs.vmware.com and knife vcair shows vm destroyed](https://www.youtube.com/watch?v=5srDko69XJ0&t=530) + +## Windows + +* [vmwair-vcair.env.example](https://www.youtube.com/watch?v=k8OZII4UGZs&t=09) +* [.kitchen.vcair.yml](https://www.youtube.com/watch?v=k8OZII4UGZs&t=20) +* [.yml / platforms:customization_script note](https://www.youtube.com/watch?v=k8OZII4UGZs&t=30) +* [customization_script install-winrm-vcair.bat](https://www.youtube.com/watch?v=k8OZII4UGZs&t=37) +* [git clone opscode-cookbooks/iis](https://www.youtube.com/watch?v=k8OZII4UGZs&t=54) +* [start coping files into iis cookbooks](https://www.youtube.com/watch?v=k8OZII4UGZs&t=60) +* [Add kitchen-vcair and kitchen-pester to the Gemfile](https://www.youtube.com/watch?v=k8OZII4UGZs&t=98) +* [bundle install kitchen vcair and pester](https://www.youtube.com/watch?v=k8OZII4UGZs&t=120) +* [KITCHEN_YAML=.kitchen.vcair.yml bundle exec kitchen verify](https://www.youtube.com/watch?v=k8OZII4UGZs&t=150) +* [Server is allocated.](https://www.youtube.com/watch?v=k8OZII4UGZs&t=270) +* ['pre'/'post' customization script ](https://www.youtube.com/watch?v=k8OZII4UGZs&t=300) +* ['pre' customization reboot ](https://www.youtube.com/watch?v=k8OZII4UGZs&t=412) +* ['post' customization boot ](https://www.youtube.com/watch?v=k8OZII4UGZs&t=440) +* [winrm is online](https://www.youtube.com/watch?v=k8OZII4UGZs&t=555) +* [installing chef omnibus](https://www.youtube.com/watch?v=k8OZII4UGZs&t=560) +* [chef-client starts](https://www.youtube.com/watch?v=k8OZII4UGZs&t=600) +* [iis:default recipe runs](https://www.youtube.com/watch?v=k8OZII4UGZs&t=630) +* [verification via kitche-pester](https://www.youtube.com/watch?v=k8OZII4UGZs&t=647) +* [kitchen verify complete!](https://www.youtube.com/watch?v=k8OZII4UGZs&t=660) +* [iis default web page via links](https://www.youtube.com/watch?v=k8OZII4UGZs&t=695) +* [kitchen verify again](https://www.youtube.com/watch?v=k8OZII4UGZs&t=710) +* [kitchen destroy](https://www.youtube.com/watch?v=k8OZII4UGZs&t=735) diff --git a/examples/httpd-cookbook/.kitchen.vcair.yml b/examples/httpd-cookbook/.kitchen.vcair.yml deleted file mode 100644 index a93f1c3..0000000 --- a/examples/httpd-cookbook/.kitchen.vcair.yml +++ /dev/null @@ -1,26 +0,0 @@ ---- -driver_config: - vcair_username: <%= ENV['VCAIR_USERNAMEX'] %> - vcair_password: <%= ENV['VCAIR_PASSWORDX'] %> - vcair_api_host: <%= ENV['VCAIR_API_HOSTX'] %> - vcair_org: <%= ENV['VCAIR_ORGX'] %> - -provisioner: - name: chef_zero - require_chef_omnibus: latest - -platforms: -- name: centos-6.4 - driver_plugin: vcair - driver_config: - size: 2gb - image: centos-6-4-x64 - vcair_ssh_password: <%= ENV['VCAIR_SSH_PASSWORDX'] %> - -suites: - # - # hello_world_test - # - - name: hello_world_test - run_list: - - recipe[hello_world_test] diff --git a/examples/windows_customization.bat b/examples/windows_customization.bat new file mode 100644 index 0000000..35eb56a --- /dev/null +++ b/examples/windows_customization.bat @@ -0,0 +1,53 @@ +@echo off + +@rem First Boot... +if “%1%” == “precustomization” ( + +echo Do precustomization tasks +@rem during this boot the hostname is set, which requires a reboot + +@rem we also enable winrm over http, plaintext, long timeout, more memory etc + +cmd.exe /c winrm quickconfig -q +cmd.exe /c winrm quickconfig -transport:http +cmd.exe /c winrm set winrm/config @{MaxTimeoutms="1800000"} +cmd.exe /c winrm set winrm/config/winrs @{MaxMemoryPerShellMB="300"} +cmd.exe /c winrm set winrm/config/service @{AllowUnencrypted="true"} +cmd.exe /c winrm set winrm/config/service/auth @{Basic="true"} +cmd.exe /c winrm set winrm/config/client/auth @{Basic="true"} +cmd.exe /c winrm set winrm/config/listener?Address=*+Transport=HTTP @{Port="5985"} + +@rem Make sure winrm is off for this boot, but enabled on next +@rem as we don't want a tcp connection available until we are +@rem past postcustomization + +cmd.exe /c net stop winrm +cmd.exe /c sc config winrm start= auto + +@rem make sure the default on password age is unlimited +@rem this ensures we don't have a password change forced on us +cmd.exe /c net accounts /maxpwage:unlimited + +@rem write out a timestamp for this first boot / customization completes +echo %DATE% %TIME% > C:\vm-is-customized + +) else if “%1%” == “postcustomization” ( + +@rem Second Boot / start winrm, just incase, and fix firewall + +cmd.exe /c net start winrm +cmd.exe /c netsh advfirewall firewall set rule group="remote administration" new enable=yes +cmd.exe /c netsh firewall add portopening TCP 5985 "Port 5985 for WinRM" + +@rem Password Setting and Autologin currently seem broken +@rem when done via the API, so we MUST set it in the postcustomization phase +cmd.exe /c net user administrator Password1 + +@rem in some environments we found the need to specify a DNS address +@rem cmd.exe /c netsh interface ipv4 add dnsserver "Ethernet" address=8.8.8.8 +@rem cmd.exe /c netsh interface ipv4 add dnsserver "Ethernet0" address=8.8.8.8 + +@rem this is our 'ready' boot, password and winrm should be up +echo %DATE% %TIME% > C:\vm-is-ready + +) diff --git a/kitchen-vcair.gemspec b/kitchen-vcair.gemspec index fde858c..0fef255 100644 --- a/kitchen-vcair.gemspec +++ b/kitchen-vcair.gemspec @@ -7,12 +7,12 @@ require 'kitchen/driver/vcair_version' Gem::Specification.new do |spec| spec.name = 'kitchen-vcair' spec.version = Kitchen::Driver::VCAIR_VERSION - spec.authors = ['Taylor Carpenter', 'Chris McClimans'] - spec.email = %w(wolfpack+c+t@vulk.co) + spec.authors = ['Chef Partner Engineering', 'Taylor Carpenter', 'Chris McClimans'] + spec.email = %w(partnereng@chef.io wolfpack+c+t@vulk.co) spec.description = 'A Test Kitchen vCloud Air driver' spec.summary = 'A Test Kitchen vCloud Air driver built on Fog' - spec.homepage = 'https://github.com/vulk/kitchen-vcair' - spec.license = 'Apache' + spec.homepage = 'https://github.com/chef-partners/kitchen-vcair' + spec.license = 'Apache 2.0' spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } @@ -21,17 +21,12 @@ Gem::Specification.new do |spec| spec.required_ruby_version = '>= 1.9.3' - spec.add_dependency 'test-kitchen', '~> 1.1' - spec.add_dependency 'pester' - spec.add_dependency 'fog', '~> 1.18' + spec.add_dependency 'test-kitchen', '~> 1.4', '>= 1.4.1' + spec.add_dependency 'fog', '~> 1.33' - spec.add_development_dependency 'bundler', '~> 1.0' - spec.add_development_dependency 'rake', '~> 10.0' - spec.add_development_dependency 'rubocop', '~> 0.29' - spec.add_development_dependency 'cane', '~> 2.6' - spec.add_development_dependency 'countloc', '~> 0.4' - spec.add_development_dependency 'rspec', '~> 3.0' - spec.add_development_dependency 'simplecov', '~> 0.9' - spec.add_development_dependency 'simplecov-console', '~> 0.2' - spec.add_development_dependency 'coveralls', '~> 0.8' + spec.add_development_dependency 'bundler', '~> 1.7' + spec.add_development_dependency 'rake', '~> 10.0' + spec.add_development_dependency 'rspec', '~> 3.2' + spec.add_development_dependency 'rubocop', '~> 0.33' + spec.add_development_dependency 'pry', '~> 0.10' end diff --git a/lib/kitchen/driver/vcair.rb b/lib/kitchen/driver/vcair.rb index 395010c..3b9a5c5 100644 --- a/lib/kitchen/driver/vcair.rb +++ b/lib/kitchen/driver/vcair.rb @@ -2,8 +2,9 @@ # # Authors:: Chris McClimans () # Authors:: Taylor Carpenter () -# -# Copyright (C) 2015, Vulk +# Authors:: Chef Partner Engineering () +# Copyright:: Copyright (c) 2015 Chef Software, Inc. +# License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -17,417 +18,341 @@ # See the License for the specific language governing permissions and # limitations under the License. -require 'benchmark' require 'fog' require 'kitchen' -require 'etc' -require 'socket' -require 'pp' +require 'securerandom' module Kitchen module Driver - # vCloud Air driver for Kitchen. - # class Vcair < Kitchen::Driver::Base - default_config :version, 'v2' - default_config :flavor_id, 'performance1-1' - default_config :username, 'root' - default_config :port, '22' - default_config :wait_for, 600 -# default_config :no_ssh_tcp_check, false - default_config :no_ssh_tcp_check, true - default_config :no_ssh_tcp_check_sleep, 120 - default_config :servicenet, false - default_config(:image_id) { |driver| driver.default_image } - default_config(:server_name) { |driver| driver.default_name } - default_config :networks, nil - default_config :vcair_show_progress, false - - default_config :vcair_username do - ENV['VCAIR_USERNAME'] - end - - default_config :vcair_password do - ENV['VCAIR_PASSWORD'] - end - - default_config :vcair_api_host do - ENV['VCAIR_API_HOST'] - end - - default_config :vcair_org do - ENV['VCAIR_ORG'] - end - - # default_config :vcloud_director_username do - # config[:vcair_username] || ENV['VCAIR_USERNAME'] - # end - # - # default_config :vcloud_director_password do - # config[:vcair_password] || ENV['VCAIR_PASSWORD'] - # end - - # default_config :vcloud_director_api_host do - # config[:vcair_api_host] || ENV['VCAIR_API_HOST'] - # end + attr_accessor :vapp_id - # default_config :vcloud_director_org do - # config[:vcair_org] || ENV['VCAIR_ORG'] - # end - - default_config :vcair_vm_password do - ENV['VCAIR_VM_PASSWORD'] - end + default_config :wait_for, 600 + default_config :vcair_api_path, '/api' + default_config :catalog_id, nil + default_config :catalog_name, nil + default_config :image_id, nil + default_config :image_name, nil + default_config :vdc_id, nil + default_config :vdc_name, nil + default_config :network_id, nil + default_config :network_name, nil + default_config :cpus, 1 + default_config :memory, 1024 + default_config :vm_password required_config :vcair_username required_config :vcair_password required_config :vcair_api_host required_config :vcair_org - required_config :image_id - required_config :vcair_vm_password - #required_config :public_key_path def initialize(config) super Fog.timeout = config[:wait_for].to_i + end - # NOTE: this is for compatibility with fog - config[:vcloud_director_org] = config[:vcair_org] || ENV['VCAIR_ORG'] - config[:vcloud_director_api_host] = config[:vcair_api_host] || ENV['VCAIR_API_HOST'] - config[:vcloud_director_username] = config[:vcair_username] || ENV['VCAIR_USERNAME'] - config[:vcloud_director_password] = config[:vcair_password] || ENV['VCAIR_PASSWORD'] + def name + 'vCloudAir' end def create(state) - server = create_server - state[:server_id] = server.id - info("vCloud Air instance <#{state[:server_id]}> created.") - server.wait_for { ready? } - puts '(server ready)' - state[:hostname] = hostname(server) - state[:password] = config[:vcair_vm_password] - # would be better to do a tcp_check here - sleep(500) - # tcp_check(state) - rescue Fog::Errors::Error, Excon::Errors::Error => ex - raise ActionFailed, ex.message - end - - - def destroy_machine(action_handler, machine_spec, machine_options) - server = server_for(machine_spec) - if server && server.status != 'archive' # TODO: does Vcair do archive? - action_handler.perform_action "destroy machine #{machine_spec.name} (#{machine_spec.location['server_id']} at #{driver_url})" do - #NOTE: currently doing 1 vm for 1 vapp - vapp = vdc.vapps.get_by_name(machine_spec.name) - if vapp - vapp.power_off - vapp.undeploy - vapp.destroy - else - Chef::Log.warn "No VApp named '#{server_name}' was found." - end - end - end - machine_spec.location = nil - strategy = convergence_strategy_for(machine_spec, machine_options) - strategy.cleanup_convergence(action_handler, machine_spec) + return unless state[:vapp_id].nil? + + validate! + + create_server(state) + vm.wait_for { ready? } + state[:hostname] = vm.ip_address + + info("Server #{state[:hostname]} is powered on. Waiting for it to be ready...") + wait_for_server(state) end def destroy(state) - return if state[:server_id].nil? - begin - vapp = vdc.vapps.get(state[:server_id]) - rescue Fog::Compute::VcloudDirector::Forbidden => e - vapp = nil - rescue Exception => e - info("VApp <#{state[:server_id]}> not found!") - end - if vapp - vapp.power_off - vapp.undeploy - vapp.destroy - info("VApp <#{state[:server_id]}> destroyed.") - else - warn("VApp <#{state[:server_id]}> not found!") - end - state.delete(:server_id) - state.delete(:hostname) - end - - def default_image - 'CentOS64-64BIT' - end - - # Generate what should be a unique server name up to 63 total chars - # Base name: 3 - # Username: 3 - # Hostname: 3 - # Random string: 3 - # Separators: 3 - # ================ - # Total: 15 (3x5) - # FIXME: Windows only supports 15 character hostnames - def default_name - [ - instance.name.gsub(/\W/, '')[0..2], - (Etc.getlogin || 'nologin').gsub(/\W/, '')[0..2], - Socket.gethostname.gsub(/\W/, '')[0..2], - Array.new(3) { rand(36).to_s(36) }.join - ].join('-') - end - - private - - def compute - server_def = { provider: 'vclouddirector' } # fog driver for vcair - opts = [:vcair_username, :vcair_password, :vcair_api_host] - opts.each do |opt| - # map vcair to vcloud_director fog naming - case opt - when :vcair_username - username = [config[opt], config[:vcair_org]].join('@') - server_def[:vcloud_director_username] = username - when :vcair_password - server_def[:vcloud_director_password] = config[opt] - when :vcair_api_host - server_def[:vcloud_director_host] = config[opt] - when :vcair_api_version - server_def[:vcloud_director_api_version] = config[opt] - when :vcair_show_progress - server_def[:vcloud_director_show_progress] = config[opt] - else - server_def[opt] = config[opt] - end - end + return if state[:vapp_id].nil? + + validate! + + self.vapp_id = state[:vapp_id] + + info("Destroying vApp #{vapp_id}...") begin - Fog::Compute.new(server_def) - rescue Excon::Errors::Unauthorized => e - error_message = "Connection failure, please check your username and password." - Chef::Log.error(error_message) - raise "#{e.message}. #{error_message}" - rescue Excon::Errors::SocketError => e - error_message = "Connection failure, please check your authentication URL." - Chef::Log.error(error_message) - raise "#{e.message}. #{error_message}" + vapp + rescue Fog::Compute::VcloudDirector::Forbidden + warn("Unable to locate vApp <#{state[:vapp_id]}> - assuming it is already destroyed.") + return end + + info('Powering off the vApp...') + vapp.power_off + + info('Undeploying the vApp...') + vapp.undeploy + + info('Deleting the vApp...') + vapp.destroy + + info("vApp <#{state[:vapp_id]}> destroyed.") end - def create_server - server_def = { name: config[:server_name], networks: networks } - [:image_id, - :flavor_id, - :public_key_path, - :customization_script, - :vcair_vm_password - ].each do |opt| - server_def[opt] = config[opt] - end + def vcloud_client + @vcloud_client ||= Fog::Compute.new(fog_server_def) + rescue Excon::Errors::Unauthorized => e + raise "Connection failure, please check your username and password. -- #{e.message}" + end + + def org + @org ||= vcloud_client.organizations.get_by_name(config[:vcair_org]) + end + def create_server(state) + self.vapp_id = instantiate + state[:vapp_id] = vapp_id - server_def[:image_name] = config[:image_id] || config[:image_name] - # Prevent destructive operations on bootstrap_options - clean_bootstrap_options = Marshal.load(Marshal.dump(server_def)) - bootstrap_options = clean_bootstrap_options - bootstrap_options[:name] = default_name.gsub(/\W/,"-").slice(0..14) + info("vApp ID #{vapp_id} created.") - begin - instantiate(clean_bootstrap_options) - vapp = vdc.vapps.get_by_name(bootstrap_options[:name]) - vm = vapp.vms.find {|v| v.vapp_name == bootstrap_options[:name]} - - update_customization(clean_bootstrap_options, vm) - if clean_bootstrap_options[:cpus] - vm.cpu = bootstrap_options[:cpus] - end - if clean_bootstrap_options[:memory] - vm.memory = bootstrap_options[:memory] - end - update_network(clean_bootstrap_options, vapp, vm) - - rescue Excon::Errors::BadRequest => e - response = Chef::JSONCompat.from_json(e.response.body) - if response['badRequest']['code'] == 400 - message = "Bad request (400): #{response['badRequest']['message']}" - Chef::Log.error(message) - else - message = "Unknown server error (#{response['badRequest']['code']}): #{response['badRequest']['message']}" - Chef::Log.error(message) - end - raise message - rescue Fog::Errors::Error => e - raise e.message + info('Validating the vApp...') + unless validate_vapp + destroy(state) + return end - vm.power_on - yield vm if block_given? - vm + info('Updating the VM customization...') + update_customization + + info('Adjusting VM hardware...') + adjust_hardware + + info('Attaching it to the network...') + attach_network + + info('Tagging the VM...') + tag_vm + + info('Powering on the VM...') + power_on end - def images - @images ||= begin - json_file = File.expand_path('../../../../data/images.json', __FILE__) - JSON.load(IO.read(json_file)) - end + def adjust_hardware + vm.cpu = config[:cpus] if config[:cpus] + vm.memory = config[:memory] if config[:memory] + end + + def attach_network_payload + { + PrimaryNetworkConnectionIndex: 0, + NetworkConnection: [ + { + network: network.name, + needsCustomization: true, + NetworkConnectionIndex: 0, + IsConnected: true, + IpAddressAllocationMode: 'POOL' + } + ] + } end - # Blocks until a TCP socket is available where a remote SSH server - # should be listening. - # - # @param hostname [String] remote SSH server host - # @param username [String] SSH username (default: `nil`) - # @param options [Hash] configuration hash (default: `{}`) - # @api private - # def wait_for_sshd(hostname, username = nil, options = {}) - # pseudo_state = { :hostname => hostname } - # pseudo_state[:username] = username if username - # pseudo_state.merge!(options) + def attach_network + task = vcloud_client.put_network_connection_system_section_vapp(vm.id, attach_network_payload) + vcloud_client.process_task(task.body) + end - # instance.transport.connection(backcompat_merged_state(pseudo_state)). - # wait_until_ready - # end + def tag_vm + vm.tags.create('created-by', 'test-kitchen') + end + def power_on + vapp.power_on + end - # def tcp_check(state) - # # allow driver config to bypass SSH tcp check -- because - # # it doesn't respect ssh_config values that might be required - # # FIXME: wait_for_sshd doesn't exist - # # we need this for winrm - # wait_for_sshd(state[:hostname]) unless config[:no_ssh_tcp_check] - # sleep(config[:no_ssh_tcp_check_sleep]) if config[:no_ssh_tcp_check] - # puts '(ssh ready)' - # end + def wait_for_server(state) + instance.transport.connection(state).wait_until_ready + rescue + error("Server #{vapp.id} (#{vm.name}) not reachable. Destroying server...") + destroy(state) + raise + end - def hostname(server) - # we don't trust dns yet - server.ip_address + def vcloud_username + [ config[:vcair_username], config[:vcair_org] ].join('@') end - def networks - base_nets = %w( - 00000000-0000-0000-0000-000000000000 - 11111111-1111-1111-1111-111111111111 - ) - config[:networks] ? base_nets + config[:networks] : nil + def fog_server_def + { + provider: 'vclouddirector', + vcloud_director_username: vcloud_username, + vcloud_director_password: config[:vcair_password], + vcloud_director_host: config[:vcair_api_host], + vcloud_director_api_version: config[:vcair_api_version], + vcloud_director_show_progress: false, + path: config[:vcair_api_path] + } end + def image + if config[:image_id] + catalog.catalog_items.get(config[:image_id]) + else + catalog.catalog_items.get_by_name(config[:image_name]) + end + end - def org - @org ||= compute.organizations.get_by_name(config[:vcair_org]) + def catalog + if config[:catalog_id] + org.catalogs.get(config[:catalog_id]) + else + org.catalogs.get_by_name(config[:catalog_name]) + end end def vdc - if config[:vcair_vdc] - @vdc ||= org.vdcs.get_by_name(config[:vcair_vdc]) + if config[:vdc_id] + org.vdcs.get(config[:vdc_id]) else - @vdc ||= org.vdcs.first + org.vdcs.get_by_name(config[:vdc_name]) end end - - def net - if config[:vcair_net] - @net ||= org.networks.get_by_name(config[:vcair_net]) + def network + if config[:network_id] + org.networks.get(config[:network_id]) else - # Grab first non-isolated (bridged, natRouted) network - @net ||= org.networks.find { |n| n if !n.fence_mode.match("isolated") } + org.networks.get_by_name(config[:network_name]) end end - def template(bootstrap_options) - # TODO: find by catalog item ID and/or NAME - # TODO: add option to search just public and/or private catalogs - tmpl=org.catalogs.map do |cat| - #cat.catalog_items.get_by_name(config(:image_id)) - cat.catalog_items.get_by_name(bootstrap_options[:image_name]) - end.compact.first - tmpl + def node_description + config[:node_description] || "Test Kitchen: #{node_name}" end - def instantiate(bootstrap_options) - begin - #node_name = config_value(:chef_node_name) - #node_name = bootstrap_options[:name] - node_name = bootstrap_options[:name] - template(bootstrap_options).instantiate( - node_name, - vdc_id: vdc.id, - network_id: net.id, - description: "id:#{node_name}") - #rescue CloudExceptions::ServerCreateError => e - rescue => e - raise e + def node_name + config[:node_name] || generate_node_name + end + + def generate_node_name + # SecureRandom.hex generates a string 2x the argument. + # We need the name to be 15 chars or less to play nicely + # with windows, so we're generating a 12-char random + # string prefixed with "tk-" + 'tk-' + SecureRandom.hex(6) + end + + def instantiate_config + { + vdc_id: vdc.id, + network_id: network.id, + description: node_description + } + end + + def print_error_and_exit(message) + error(message) + fail message + end + + def validate! + %w(vdc catalog image network).each do |param| + validate_parameter_pair!(param) + end + + [ :org, :vdc, :catalog, :image, :network].each do |method| + validate_method!(method) end + + validate_customization_script! + validate_computer_name! + end + + def validate_parameter_pair!(param) + id_key = param + '_id' + name_key = param + '_name' + + print_error_and_exit("No #{param} found. You must specify #{id_key} or #{name_key}.") if + config[id_key.to_sym].nil? && config[name_key.to_sym].nil? + end + + def validate_method!(method) + send(method) + rescue => e + raise "Unable to validate #{method} - check your configuration and try again. #{e.class} -- #{e.message}" + end + + def validate_computer_name! + # regex proudly modified after stealing from: + # http://stackoverflow.com/questions/2063213/regular-expression-for-validating-dns-label-host-name + print_error_and_exit('Node name is not valid - must be 15 characters or less, and be a valid Windows node name') unless + node_name =~ /^(?![0-9]+$)(?!-)[a-zA-Z0-9-]{,15}(? 1 + error('vApp created, but contained more than one VM') + return false end - # DNS and Windows want AlphaNumeric and dashes for hostnames - # Windows can only handle 15 character hostnames - # TODO: only change name for Windows! - custom.computer_name = bootstrap_options[:name].gsub(/\W/,"-").slice(0..14) - # FIXME, names ending in - don't work either - custom.computer_name = custom.computer_name.gsub(/-$/,"").slice(0..14) - custom.enabled = true - custom.save - end - - ## Vcair - ## TODO: make work with floating_ip - ## NOTE: current vcair networking changes require VM to be powered off - def update_network(bootstrap_options, vapp, vm) - ## TODO: allow user to specify network to connect to (see above net used) - # Define network connection for vm based on existing routed network - - # Vcair inlining vapp() and vm() - #vapp = vdc.vapps.get_by_name(bootstrap_options[:name]) - #vm = vapp.vms.find {|v| v.vapp_name == bootstrap_options[:name]} - nc = vapp.network_config.find { |n| n if n[:networkName].match(net.name) } - networks_config = [nc] - section = {PrimaryNetworkConnectionIndex: 0} - section[:NetworkConnection] = networks_config.compact.each_with_index.map do |network, i| - connection = { - network: network[:networkName], - needsCustomization: true, - NetworkConnectionIndex: i, - IsConnected: true - } - ip_address = network[:ip_address] - ## TODO: support config options for allocation mode - #allocation_mode = network[:allocation_mode] - #allocation_mode = 'manual' if ip_address - #allocation_mode = 'dhcp' unless %w{dhcp manual pool}.include?(allocation_mode) - #allocation_mode = 'POOL' - #connection[:Dns1] = dns1 if dns1 - allocation_mode = 'pool' - connection[:IpAddressAllocationMode] = allocation_mode.upcase - connection[:IpAddress] = ip_address if ip_address - connection + true + end + + def customization + @customization ||= vm.customization + end + + def update_customization + set_customization_script if config[:customization_script] + set_customization_password + set_customization_computer_name + save_customization + end + + def set_customization_script + customization.script = ::File.read(config[:customization_script]) + end + + def set_customization_password + if config[:vm_password] + customization.admin_password = config[:vm_password] + customization.admin_password_auto = false + customization.reset_password_required = false + else + customization.admin_password = nil + customization.admin_password_auto = true + customization.reset_password_required = false end + end + + def set_customization_computer_name + customization.computer_name = node_name + end - ## attach the network to the vm - nc_task = compute.put_network_connection_system_section_vapp( - vm.id,section).body - compute.process_task(nc_task) + def save_customization + customization.enabled = true + customization.save end end end diff --git a/lib/kitchen/driver/vcair_version.rb b/lib/kitchen/driver/vcair_version.rb index 434388a..1dcad5e 100644 --- a/lib/kitchen/driver/vcair_version.rb +++ b/lib/kitchen/driver/vcair_version.rb @@ -2,8 +2,9 @@ # # Authors:: Chris McClimans () # Authors:: Taylor Carpenter () -# -# Copyright (C) 2015, Vulk +# Authors:: Chef Partner Engineering () +# Copyright:: Copyright (c) 2015 Chef Software, Inc. +# License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -18,10 +19,7 @@ # limitations under the License. module Kitchen - # Version string for vCloud Air Kitchen driver - # - # @author Chris McClimans and Taylor Carpenter module Driver - VCAIR_VERSION = '0.1.1' + VCAIR_VERSION = '1.0.0' end end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb new file mode 100644 index 0000000..b1ce97f --- /dev/null +++ b/spec/spec_helper.rb @@ -0,0 +1,17 @@ +# Encoding: UTF-8 +# +# Authors:: Chef Partner Engineering () +# Copyright:: Copyright (c) 2015 Chef Software, Inc. +# License:: Apache License, Version 2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/spec/vcair_spec.rb b/spec/vcair_spec.rb new file mode 100644 index 0000000..54262e3 --- /dev/null +++ b/spec/vcair_spec.rb @@ -0,0 +1,825 @@ +# Encoding: UTF-8 +# +# Authors:: Chef Partner Engineering () +# Copyright:: Copyright (c) 2015 Chef Software, Inc. +# License:: Apache License, Version 2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +require 'spec_helper' +require 'excon' +require 'kitchen/driver/vcair' +require 'kitchen/provisioner/dummy' +require 'kitchen/transport/dummy' +require 'kitchen/verifier/dummy' + +describe Kitchen::Driver::Vcair do + let(:logged_output) { StringIO.new } + let(:logger) { Logger.new(logged_output) } + let(:platform) { Kitchen::Platform.new(name: 'fake_platform') } + let(:transport) { Kitchen::Transport::Dummy.new } + let(:driver) { Kitchen::Driver::Vcair.new(config) } + + let(:config) do + { + vcair_username: 'myuser', + vcair_password: 'mypassword', + vcair_api_host: 'https://vcloud.air', + vcair_api_path: '/api/compute/api', + vcair_org: 'myorg', + cpus: 2, + memory: 2048, + vdc_id: 1, + catalog_id: 2, + image_id: 3, + network_id: 4 + } + end + + let(:instance) do + instance_double(Kitchen::Instance, + logger: logger, + transport: transport, + platform: platform, + to_str: 'instance_str' + ) + end + + before do + allow(driver).to receive(:instance).and_return(instance) + end + + describe '#create' do + context 'when the server is already created' do + let(:state) { { vapp_id: 'vapp1' } } + it 'does not call create_server' do + expect(driver).not_to receive(:create_server) + end + end + + context 'when the server is not yet created' do + let(:state) { {} } + let(:vm) { double('vm') } + + it 'calls the expected methods' do + allow(driver).to receive(:vm).and_return(vm) + allow(driver.vm).to receive(:ip_address).and_return('1.2.3.4') + + expect(driver).to receive(:validate!) + expect(driver).to receive(:create_server).with(state) + expect(driver.vm).to receive(:wait_for) + expect(driver).to receive(:wait_for_server).with(state) + + driver.create(state) + end + end + end + + describe '#destroy' do + context 'when the server does not exist' do + let(:state) { {} } + it 'does not fetch the vapp' do + expect(driver).not_to receive(:vapp) + + driver.destroy(state) + end + end + + context 'when the server exists' do + let(:state) { { vapp_id: 'vapp1' } } + let(:vapp) { double('vapp') } + before do + allow(driver).to receive(:validate!) + allow(driver).to receive(:vapp).and_return(vapp) + allow(vapp).to receive(:power_off) + allow(vapp).to receive(:undeploy) + allow(vapp).to receive(:destroy) + end + + it 'calls validate!' do + expect(driver).to receive(:validate!) + driver.destroy(state) + end + + it 'sets the vapp_id' do + expect(driver).to receive(:vapp_id=).with('vapp1') + driver.destroy(state) + end + + context 'when the vapp does not exist' do + it 'does not call vapp again to power_off, etc.' do + expect(driver).to receive(:vapp).once.and_raise(Fog::Compute::VcloudDirector::Forbidden) + driver.destroy(state) + end + end + + it 'fetches the vapp' do + expect(driver).to receive(:vapp) + driver.destroy(state) + end + + it 'gets rid of the vapp' do + expect(driver.vapp).to receive(:power_off) + expect(driver.vapp).to receive(:undeploy) + expect(driver.vapp).to receive(:destroy) + + driver.destroy(state) + end + end + end + + describe '#vcloud_client' do + let(:fog_server_def) { double('fog_server_def') } + let(:client) { double('client') } + + before do + allow(driver).to receive(:fog_server_def).and_return(fog_server_def) + end + + it 'sets up a new Fog::Compute instance' do + expect(Fog::Compute).to receive(:new).with(fog_server_def).and_return(client) + expect(driver.vcloud_client).to eq(client) + end + + it 'raises an error if unauthorized' do + allow(Fog::Compute).to receive(:new).and_raise(Excon::Errors::Unauthorized, 'auth failed') + expect { driver.vcloud_client }.to raise_error( + RuntimeError, + 'Connection failure, please check your username and password. -- auth failed' + ) + end + end + + describe '#org' do + let(:client) { double('client') } + let(:organizations) { double('organizations') } + let(:org) { double('org') } + + it 'fetches the organization by name' do + allow(driver).to receive(:vcloud_client).and_return(client) + allow(client).to receive(:organizations).and_return(organizations) + expect(organizations).to receive(:get_by_name).with('myorg').and_return(org) + expect(driver.org).to eq(org) + end + end + + describe '#create_server' do + let(:state) { {} } + + it 'calls the expected methods' do + expect(driver).to receive(:instantiate).and_return('vapp1') + expect(driver).to receive(:vapp_id=).with('vapp1') + expect(driver).to receive(:validate_vapp).and_return(true) + expect(driver).to receive(:update_customization) + expect(driver).to receive(:adjust_hardware) + expect(driver).to receive(:attach_network) + expect(driver).to receive(:tag_vm) + expect(driver).to receive(:power_on) + + driver.create_server(state) + end + + context 'when the vapp validation fails' do + before do + allow(driver).to receive(:instantiate) + allow(driver).to receive(:validate_vapp).and_return(false) + end + + it 'destroys the server' do + expect(driver).to receive(:destroy).with(state) + driver.create_server(state) + end + + it 'does not power on the vapp' do + expect(driver).not_to receive(:power_on) + driver.create_server(state) + end + end + end + + describe '#adjust_hardware' do + let(:vm) { double('vm') } + before do + allow(driver).to receive(:vm).and_return(vm) + end + + context 'when config parameters are supplied' do + it 'sets the cpus and memory on the VM' do + expect(vm).to receive(:cpu=).with(2) + expect(vm).to receive(:memory=).with(2048) + + driver.adjust_hardware + end + end + + context 'when config parameters are not supplied' do + before do + config[:cpus] = nil + config[:memory] = nil + end + + it 'does not set the cpus and memory on the VM' do + expect(vm).not_to receive(:cpu=) + expect(vm).not_to receive(:memory=) + + driver.adjust_hardware + end + end + end + + describe '#attach_network' do + let(:client) { double('client') } + let(:payload) { {} } + let(:task) { double('task', body: 'body text') } + let(:vm) { double('vm', id: 'vm1') } + + it 'submits the request and processes it' do + allow(driver).to receive(:vcloud_client).and_return(client) + allow(driver).to receive(:attach_network_payload).and_return(payload) + allow(driver).to receive(:vm).and_return(vm) + + expect(client).to receive(:put_network_connection_system_section_vapp) + .with('vm1', payload).and_return(task) + expect(client).to receive(:process_task).with('body text') + + driver.attach_network + end + end + + describe '#tag_vm' do + let(:vm) { double('vm') } + let(:tags) { double('tags') } + + it 'tags the VM' do + allow(driver).to receive(:vm).and_return(vm) + allow(vm).to receive(:tags).and_return(tags) + expect(tags).to receive(:create).with('created-by', 'test-kitchen') + + driver.tag_vm + end + end + + describe '#power_on' do + let(:vapp) { double('vapp') } + + it 'powers on the vApp' do + allow(driver).to receive(:vapp).and_return(vapp) + expect(vapp).to receive(:power_on) + + driver.power_on + end + end + + describe '#wait_for_server' do + let(:connection) { instance.transport.connection(state) } + let(:state) { {} } + let(:vapp) { double('vapp', id: 'vapp1') } + let(:vm) { double('vm', name: 'vm1') } + + before do + allow(transport).to receive(:connection).and_return(connection) + allow(driver).to receive(:vapp).and_return(vapp) + allow(driver).to receive(:vm).and_return(vm) + end + + it 'calls wait_until_ready on the transport connection' do + expect(connection).to receive(:wait_until_ready) + driver.wait_for_server(state) + end + + it 'destroys the vApp if the server failed to become ready' do + allow(connection).to receive(:wait_until_ready).and_raise(RuntimeError) + expect(driver).to receive(:destroy).with(state) + expect { driver.wait_for_server(state) }.to raise_error(RuntimeError) + end + end + + describe '#vcloud_username' do + it 'returns a properly-formatted username' do + expect(driver.vcloud_username).to eq('myuser@myorg') + end + end + + describe '#image' do + let(:catalog) { double('catalog') } + let(:catalog_items) { double('catalog_items') } + + before do + allow(driver).to receive(:catalog).and_return(catalog) + allow(catalog).to receive(:catalog_items).and_return(catalog_items) + end + + context 'when an ID is provided' do + before do + config[:image_id] = 1 + config[:image_name] = nil + end + + it 'fetches the catalog item by ID' do + expect(catalog_items).to receive(:get).with(1) + driver.image + end + end + + context 'when a name is provided' do + before do + config[:image_id] = nil + config[:image_name] = 'image name' + end + + it 'fetches the catalog item by name' do + expect(catalog_items).to receive(:get_by_name).with('image name') + driver.image + end + end + end + + describe '#catalog' do + let(:org) { double('org') } + let(:catalogs) { double('catalogs') } + + before do + allow(driver).to receive(:org).and_return(org) + allow(org).to receive(:catalogs).and_return(catalogs) + end + + context 'when an ID is provided' do + before do + config[:catalog_id] = 1 + config[:catalog_name] = nil + end + + it 'fetches the catalog by ID' do + expect(catalogs).to receive(:get).with(1) + driver.catalog + end + end + + context 'when a name is provided' do + before do + config[:catalog_id] = nil + config[:catalog_name] = 'catalog name' + end + + it 'fetches the catalog by name' do + expect(catalogs).to receive(:get_by_name).with('catalog name') + driver.catalog + end + end + end + + describe '#vdc' do + let(:org) { double('org') } + let(:vdcs) { double('vdcs') } + + before do + allow(driver).to receive(:org).and_return(org) + allow(org).to receive(:vdcs).and_return(vdcs) + end + + context 'when an ID is provided' do + before do + config[:vdc_id] = 1 + config[:vdc_name] = nil + end + + it 'fetches the vdc by ID' do + expect(vdcs).to receive(:get).with(1) + driver.vdc + end + end + + context 'when a name is provided' do + before do + config[:vdc_id] = nil + config[:vdc_name] = 'vdc name' + end + + it 'fetches the vdc by name' do + expect(vdcs).to receive(:get_by_name).with('vdc name') + driver.vdc + end + end + end + + describe '#network' do + let(:org) { double('org') } + let(:networks) { double('networks') } + + before do + allow(driver).to receive(:org).and_return(org) + allow(org).to receive(:networks).and_return(networks) + end + + context 'when an ID is provided' do + before do + config[:network_id] = 1 + config[:network_name] = nil + end + + it 'fetches the network by ID' do + expect(networks).to receive(:get).with(1) + driver.network + end + end + + context 'when a name is provided' do + before do + config[:network_id] = nil + config[:network_name] = 'network name' + end + + it 'fetches the network by name' do + expect(networks).to receive(:get_by_name).with('network name') + driver.network + end + end + end + + describe '#node_description' do + context 'when a node description is provided' do + before do + config[:node_description] = 'sample description' + end + + it 'returns the configured description' do + expect(driver.node_description).to eq('sample description') + end + end + + context 'when a node description is not provided' do + it 'returns the default description' do + allow(driver).to receive(:node_name).and_return('node') + expect(driver.node_description).to eq('Test Kitchen: node') + end + end + end + + describe '#node_name' do + context 'when a node name is provided' do + before do + config[:node_name] = 'testnode' + end + + it 'returns the configured node name' do + expect(driver.node_name).to eq('testnode') + end + end + + context 'when a node name is not provided' do + it 'returns a generated node name' do + expect(driver).to receive(:generate_node_name).and_return('a12345') + expect(driver.node_name).to eq('a12345') + end + end + end + + describe '#generate_node_name' do + it 'generates a node name using SecureRandom' do + expect(SecureRandom).to receive(:hex).with(6).and_return('randomchars') + expect(driver.generate_node_name).to eq('tk-randomchars') + end + end + + describe '#print_error_and_exit' do + it 'prints an error message and raises an exception' do + expect(driver).to receive(:error).with('error text') + expect { driver.print_error_and_exit('error text') }.to raise_error(RuntimeError) + end + end + + describe '#validate!' do + it 'calls all the expected validate methods' do + expect(driver).to receive(:validate_parameter_pair!).with('vdc') + expect(driver).to receive(:validate_parameter_pair!).with('catalog') + expect(driver).to receive(:validate_parameter_pair!).with('image') + expect(driver).to receive(:validate_parameter_pair!).with('network') + + expect(driver).to receive(:validate_method!).with(:org) + expect(driver).to receive(:validate_method!).with(:vdc) + expect(driver).to receive(:validate_method!).with(:catalog) + expect(driver).to receive(:validate_method!).with(:image) + expect(driver).to receive(:validate_method!).with(:network) + + expect(driver).to receive(:validate_customization_script!) + expect(driver).to receive(:validate_computer_name!) + + driver.validate! + end + end + + describe '#validate_parameter_pair!' do + context 'when an ID exists but not a name' do + before do + config[:test_id] = 1 + config[:test_name] = nil + end + + it 'does not print an error' do + expect(driver).not_to receive(:print_error_and_exit) + driver.validate_parameter_pair!('test') + end + end + + context 'when a name exists but not an ID' do + before do + config[:test_id] = nil + config[:test_name] = 'test' + end + + it 'does not print an error' do + expect(driver).not_to receive(:print_error_and_exit) + driver.validate_parameter_pair!('test') + end + end + + context 'when neither a name nor an ID exists' do + before do + config[:test_id] = nil + config[:test_name] = nil + end + + it 'prints an error' do + expect(driver).to receive(:print_error_and_exit) + driver.validate_parameter_pair!('test') + end + end + end + + describe '#validate_method!' do + context 'when the method is successful' do + it 'does not raise an exception' do + allow(driver).to receive(:test_method) + expect { driver.validate_method!(:test_method) }.not_to raise_error + end + end + + context 'when the method is not successful' do + it 'raises an exception' do + allow(driver).to receive(:test_method).and_raise(RuntimeError) + expect { driver.validate_method!(:test_method) }.to raise_error(RuntimeError) + end + end + end + + describe '#validate_computer_name' do + it 'allows an alphanumeric 15-char string' do + allow(driver).to receive(:node_name).and_return('a12345678901234') + expect(driver).not_to receive(:print_error_and_exit) + + driver.validate_computer_name! + end + + it 'does not allow a computer name that only has numbers' do + allow(driver).to receive(:node_name).and_return('12345') + expect(driver).to receive(:print_error_and_exit) + + driver.validate_computer_name! + end + + it 'does not allow a 16 character name' do + allow(driver).to receive(:node_name).and_return('a123456789012345') + expect(driver).to receive(:print_error_and_exit) + + driver.validate_computer_name! + end + + it 'does not allow a hyphen at the end' do + allow(driver).to receive(:node_name).and_return('a12345-') + expect(driver).to receive(:print_error_and_exit) + + driver.validate_computer_name! + end + end + + describe '#validate_customization_script!' do + context 'when no customization script has been configured' do + before do + config[:customization_script] = nil + end + + it 'does not print an error' do + expect(driver).not_to receive(:print_error_and_exit) + + driver.validate_customization_script! + end + end + + context 'when a script is configured and is readable' do + before do + config[:customization_script] = '/path/to/script' + end + + it 'does not print an error' do + expect(File).to receive(:readable?).with('/path/to/script').and_return(true) + expect(driver).not_to receive(:print_error_and_exit) + + driver.validate_customization_script! + end + end + + context 'when a script is configured but is not readable' do + before do + config[:customization_script] = '/path/to/script' + end + + it 'does not print an error' do + expect(File).to receive(:readable?).with('/path/to/script').and_return(false) + expect(driver).to receive(:print_error_and_exit) + + driver.validate_customization_script! + end + end + end + + describe '#instantiate' do + let(:image) { double('image') } + + it 'calls instantiate on the image' do + allow(driver).to receive(:image).and_return(image) + allow(driver).to receive(:node_name).and_return('node') + allow(driver).to receive(:instantiate_config).and_return('config') + expect(image).to receive(:instantiate).with('node', 'config') + + driver.instantiate + end + end + + describe '#vapp' do + let(:vdc) { double('vdc') } + let(:vapps) { double('vapps') } + let(:vapp) { double('vapp') } + + it 'gets the vApp by ID' do + allow(driver).to receive(:vapp_id).and_return('vapp1') + allow(driver).to receive(:vdc).and_return(vdc) + allow(vdc).to receive(:vapps).and_return(vapps) + expect(vapps).to receive(:get).with('vapp1').and_return(vapp) + expect(driver.vapp).to eq(vapp) + end + end + + describe '#vm' do + let(:vapp) { double('vapp') } + let(:vms) { %w(vm1 vm2) } + + it 'returns the first VM from the array' do + allow(driver).to receive(:vapp).and_return(vapp) + allow(vapp).to receive(:vms).and_return(vms) + + expect(driver.vm).to eq('vm1') + end + end + + describe '#validate_vapp' do + let(:vapp) { double('vapp') } + before do + allow(driver).to receive(:vapp).and_return(vapp) + end + + it 'returns true when only 1 VM is present' do + allow(vapp).to receive(:vms).and_return([1]) + expect(driver.validate_vapp).to eq(true) + end + + it 'returns false when 0 VMs are present' do + allow(vapp).to receive(:vms).and_return([]) + expect(driver.validate_vapp).to eq(false) + end + + it 'returns false when >1 VMs are present' do + allow(vapp).to receive(:vms).and_return([1, 2]) + expect(driver.validate_vapp).to eq(false) + end + end + + describe '#customization' do + let(:vm) { double('vm') } + let(:customization) { double('customization') } + it 'fetches the customization from the VM' do + allow(driver).to receive(:vm).and_return(vm) + expect(vm).to receive(:customization).and_return(customization) + expect(driver.customization).to eq(customization) + end + end + + describe '#update_customization' do + before do + allow(driver).to receive(:set_customization_script) + allow(driver).to receive(:set_customization_password) + allow(driver).to receive(:set_customization_computer_name) + allow(driver).to receive(:save_customization) + end + + context 'when a customization script is provided' do + before do + config[:customization_script] = '/path/to/script' + end + + it 'calls set_customization_script' do + expect(driver).to receive(:set_customization_script) + driver.update_customization + end + end + + context 'when a customization script is not provided' do + before do + config[:customization_script] = nil + end + + it 'does not call set_customization_script' do + expect(driver).not_to receive(:set_customization_script) + driver.update_customization + end + end + + it 'calls the expected methods' do + expect(driver).to receive(:set_customization_password) + expect(driver).to receive(:set_customization_computer_name) + expect(driver).to receive(:save_customization) + driver.update_customization + end + end + + describe '#set_customization_script' do + let(:customization) { double('customization') } + + before do + config[:customization_script] = '/path/to/script' + allow(driver).to receive(:customization).and_return(customization) + allow(File).to receive(:read).with('/path/to/script').and_return('script body') + end + + it 'sets the customization script to the file contents' do + expect(customization).to receive(:script=).with('script body') + driver.set_customization_script + end + end + + describe '#set_customization_password' do + let(:customization) { double('customization') } + before do + allow(driver).to receive(:customization).and_return(customization) + end + + context 'when a VM password is provided' do + before do + config[:vm_password] = 'password123' + end + + it 'sets the password and disables auto-generation and reset' do + expect(customization).to receive(:admin_password=).with('password123') + expect(customization).to receive(:admin_password_auto=).with(false) + expect(customization).to receive(:reset_password_required=).with(false) + + driver.set_customization_password + end + end + + context 'when a VM password is not provided' do + before do + config[:vm_password] = nil + end + + it 'sets nulls-out the password, enables auto-generation, disables reset reset' do + expect(customization).to receive(:admin_password=).with(nil) + expect(customization).to receive(:admin_password_auto=).with(true) + expect(customization).to receive(:reset_password_required=).with(false) + + driver.set_customization_password + end + end + end + + describe '#set_customization_computer_name' do + let(:customization) { double('customization') } + it 'sets the computer name' do + allow(driver).to receive(:customization).and_return(customization) + allow(driver).to receive(:node_name).and_return('test node') + expect(customization).to receive(:computer_name=).with('test node') + + driver.set_customization_computer_name + end + end + + describe '#save_customization' do + let(:customization) { double('customization') } + it 'enables and saves the customization' do + allow(driver).to receive(:customization).and_return(customization) + expect(customization).to receive(:enabled=).with(true) + expect(customization).to receive(:save) + + driver.save_customization + end + end +end diff --git a/using-vcair-test-kitchen-driver.mkd b/using-vcair-test-kitchen-driver.mkd deleted file mode 100644 index c4d5bf8..0000000 --- a/using-vcair-test-kitchen-driver.mkd +++ /dev/null @@ -1,92 +0,0 @@ -# Using kitchen-vcair with the httpd (Apache) cookbook - -These steps assume you have chef installed on your workstation -and access to a vClour Air environment. - -## Grab the kitchen-vcair gem - -Install the gem from source: - -``` -git clone git@github.com:vulk/kitchen-vcair.git -``` - -or whatever your favorite method is. - -## Build and install the gem if you grabbed from source/git - -Build it: -``` -cd kitchen-vcair -gem build kitchen-vcair.gemspec -``` - -Install it... eg. - -``` -gem install ./kitchen-vcair-0.1.0.gem -``` - -## Grab the the Apache (httpd) cookbook - -Install using your favorite method. Eg. with git: - -``` -git clone git@github.com:chef-cookbooks/httpd.git -``` - -## Create a test kitchen configuration file - -Go into the cookbook and create a `.kitchen.vcair.yml`. -Example: - -``` ---- -driver_config: - vcair_username: <%= ENV['VCAIR_USERNAMEX'] %> - vcair_password: <%= ENV['VCAIR_PASSWORDX'] %> - vcair_api_host: <%= ENV['VCAIR_API_HOSTX'] %> - vcair_org: <%= ENV['VCAIR_ORGX'] %> - -provisioner: - name: chef_zero - require_chef_omnibus: latest - -platforms: -- name: centos-6.4 - driver_plugin: vcair - driver_config: - size: 2gb - image: centos-6-4-x64 - vcair_ssh_password: <%= ENV['VCAIR_SSH_PASSWORDX'] %> - -suites: - # - # hello_world_test - # - - name: hello_world_test - run_list: - - recipe[hello_world_test] -``` - -## Create and load an environment configuration file - -Add vCloud Air configuration to environment. eg.: - -``` -export VCAIR_API_HOST='pNvNN-vcd.vchs.vmware.com' -export VCAIR_SSH_PASSWORD='RANDOM_PASSWORD_HERE' - -export VCAIR_ORG='MNNNNNNNNN-NNN' - -export VCAIR_USERNAME='your@example.com' -export VCAIR_PASSWORD='YOUR_VCAIR_PASSWORD' -``` - -## Run test-kitchen using the configuration created previously - -Go into the httpd cookbook directory and run - -``` -KITCHEN_YAML=".kitchen.vcair.yml" kitchen test -```