knife-kvm 0.1

Sign up to get free protection for your applications and to get access to all the features.
data/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
data/README.rdoc ADDED
@@ -0,0 +1,75 @@
1
+ = Knife KVM
2
+
3
+ = DESCRIPTION:
4
+
5
+ This is the unofficial Opscode Knife plugin for KVM. This plugin gives knife the ability to create, bootstrap, and manage virtual machines in a VMWare KVM host.
6
+
7
+ You'll need an KVM host with SSH enabled and a privileged user account to connect to it via SSH:
8
+
9
+ You'll also need a special VM template (in QCOW2/RAW) with CentOS/Ubuntu/Fedora and installed.
10
+
11
+ http://github.com/rubiojr/knife-kvm
12
+
13
+ = INSTALLATION:
14
+
15
+ Be sure you are running the latest version Chef. Versions earlier than 0.10.0 don't support plugins:
16
+
17
+ gem install chef
18
+
19
+ This plugin is distributed as a Ruby Gem. To install it, run:
20
+
21
+ gem install knife-kvm
22
+
23
+ Depending on your system's configuration, you may need to run this command with root privileges.
24
+
25
+ = CONFIGURATION:
26
+
27
+ In order to communicate with the KVM Cloud API you will have to tell Knife about your Username and API Key. The easiest way to accomplish this is to create some entries in your <tt>knife.rb</tt> file:
28
+
29
+ knife[:kvm_host] = "Your KVM host address"
30
+ knife[:kvm_username] = "root"
31
+ knife[:kvm_password] = "secret"
32
+
33
+ You also have the option of passing your KVM Host/Username/Password into the individual knife subcommands using the <tt>--kvm-host</tt> <tt>--kvm-username</tt> and <tt>--kvm-password</tt> command options
34
+
35
+ # provision a new Ubuntu 11.10 VM
36
+ knife kvm vm create --template-file ~/.chef/bootstrap/ubuntu11.10-gems.erb \
37
+ --vm-disk /path-to/ubuntu1110-x64-vmware-tools.vmdk \
38
+ --vm-name knife-kvm-test-ubuntu \
39
+ --datastore datastore1
40
+ --kvm-host my-test-host \
41
+ --kvm-password secret
42
+
43
+ = SUBCOMMANDS:
44
+
45
+ This plugin provides the following Knife subcommands. Specific command options can be found by invoking the subcommand with a <tt>--help</tt> flag
46
+
47
+ == knife kvm vm create
48
+
49
+ Provisions a new virtual machine in the KVM host and then perform a Chef bootstrap (using the SSH protocol). The goal of the bootstrap is to get Chef installed on the target system so it can run Chef Client with a Chef Server. The main assumption is a baseline OS installation exists (provided by the provisioning). It is primarily intended for Chef Client systems that talk to a Chef server. By default the virtual machine is bootstrapped using the {ubuntu10.04-gems}[https://github.com/opscode/chef/blob/master/chef/lib/chef/knife/bootstrap/ubuntu10.04-gems.erb] template. This can be overridden using the <tt>-d</tt> or <tt>--template-file</tt> command options.
50
+
51
+ == knife kvm vm delete
52
+
53
+ Deletes an existing virtual machine in the currently configured KVM host by the virtual machine name. You can find the instance id by entering 'knife kvm vm list'. Please note - this does not delete the associated node and client objects from the Chef server.
54
+
55
+ == knife kvm vm list
56
+
57
+ Outputs a list of all virtual machines in the currently configured KVM host. Please note - this shows all the virtual machines available in the KVM host, some of which may not be currently managed by the Chef server.
58
+
59
+ = LICENSE:
60
+
61
+ Author:: Sergio Rubio (<rubiojr@frameos.org>)
62
+ Copyright:: Copyright (c) 2011 Sergio Rubio
63
+ License:: Apache License, Version 2.0
64
+
65
+ Licensed under the Apache License, Version 2.0 (the "License");
66
+ you may not use this file except in compliance with the License.
67
+ You may obtain a copy of the License at
68
+
69
+ http://www.apache.org/licenses/LICENSE-2.0
70
+
71
+ Unless required by applicable law or agreed to in writing, software
72
+ distributed under the License is distributed on an "AS IS" BASIS,
73
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
74
+ See the License for the specific language governing permissions and
75
+ limitations under the License.
@@ -0,0 +1,68 @@
1
+ Feature: knife kvm
2
+
3
+ Scenario: Run kvm create vm without arguments
4
+ When I run `knife kvm vm create`
5
+ Then the output should contain:
6
+ """
7
+ ERROR: You have not provided a valid VMDK file. (--vm-disk)
8
+ """
9
+ Scenario: Print help
10
+ When I run `knife kvm --help`
11
+ Then the output should contain "Available kvm subcommands:"
12
+
13
+ Scenario: Unknown kvm create sub-command
14
+ When I run `knife kvm create foobar`
15
+ Then the output should contain "FATAL: Cannot find sub command for:"
16
+
17
+ Scenario: Invalid VMDK file
18
+ When I run `knife kvm vm create --vm-disk /tmp/foo9098jfj`
19
+ Then the output should contain "Invalid VMDK disk file (--vm-disk)"
20
+
21
+ Scenario: Missing VM name
22
+ When I run `knife kvm vm create --vm-disk /tmp/test.vmdk`
23
+ Then the output should contain "ERROR: Invalid Virtual Machine name (--vm-name)"
24
+
25
+ Scenario: Missing Host option
26
+ When I run `knife kvm vm create --vm-disk /tmp/test.vmdk --vm-name knife-kvm-test`
27
+ Then the output should contain "ERROR: RuntimeError: host option required"
28
+
29
+ Scenario: Invalid ESX host
30
+ When I run `knife kvm vm create --vm-disk /tmp/m0n0wall-stream.vmdk --vm-name knife-kvm-test --kvm-host localhost --kvm-password temporal --datastore datastore1`
31
+ Then the output should contain "ERROR: Network Error: Connection refused"
32
+
33
+ Scenario: Invalid ESX password
34
+ When I run `knife kvm vm create --vm-disk /tmp/m0n0wall-stream.vmdk --vm-name knife-kvm-test --kvm-host kvm-test-host --kvm-password oiusdf`
35
+ Then the output should contain "ERROR: RbVmomi::Fault: InvalidLogin: Cannot complete login due to an incorrect user name or password"
36
+
37
+ Scenario: Unknown host
38
+ When I run `knife kvm vm create --vm-disk /tmp/m0n0wall-stream.vmdk --vm-name knife-kvm-test --kvm-host lllocalhost --kvm-password temporal --datastore datastore1`
39
+ Then the output should contain "ERROR: Network Error: getaddrinfo: Name or service not known"
40
+
41
+ Scenario: Missing VMWare Tools in server
42
+ When I run `knife kvm vm create --vm-disk /tmp/m0n0wall-stream.vmdk --vm-name knife-kvm-test --kvm-host kvm-test-host --kvm-password temporal --datastore datastore1`
43
+ Then the output should contain "Timeout trying to reach the VM. Does it have vmware-tools installed?"
44
+
45
+ Scenario: Existing VM disk in host
46
+ When I run `knife kvm vm create --vm-disk /tmp/m0n0wall-stream.vmdk --vm-name knife-kvm-test --kvm-host kvm-test-host --kvm-password temporal --datastore datastore1`
47
+ Then the output should contain "ERROR: Exception: Destination file"
48
+
49
+ Scenario: Delete Existing VM
50
+ When I run `knife kvm vm delete --force-delete yes knife-kvm-test --kvm-host kvm-test-host --kvm-password temporal`
51
+ Then the output should contain "WARNING: Deleted virtual machine knife-kvm-test"
52
+
53
+ Scenario: Delete non-existent VM
54
+ When I run `knife kvm vm delete --force-delete yes knife-kvm-test --kvm-host kvm-test-host --kvm-password temporal`
55
+ Then the output should contain "WARNING: Virtual Machine knife-kvm-test not found"
56
+
57
+ @announce
58
+ Scenario: Success bootstraping VM
59
+ When I run `knife kvm vm create --template-file /home/rubiojr/.chef/bootstrap/ubuntu11.10-gems.erb --vm-disk /home/rubiojr/tmp/ubuntu1110-x64-vmware-tools.vmdk --vm-name knife-kvm-test-ubuntu --kvm-host kvm-test-host --kvm-password temporal --datastore datastore1 --ssh-user ubuntu --ssh-password ubuntu --no-host-key-verify`
60
+ Then the output should contain "Done!"
61
+
62
+ Scenario: List virtual machine
63
+ When I run `knife kvm vm list --kvm-host kvm-test-host --kvm-password temporal`
64
+ Then the output should contain "knife-kvm-test-ubuntu"
65
+
66
+ Scenario: Delete Existing VM
67
+ When I run `knife kvm vm delete --force-delete yes knife-kvm-test-ubuntu --kvm-host kvm-test-host --kvm-password temporal`
68
+ Then the output should contain "WARNING: Deleted virtual machine knife-kvm-test-ubuntu"
File without changes
@@ -0,0 +1,11 @@
1
+ require 'aruba/cucumber'
2
+ require 'fileutils'
3
+
4
+ Before do
5
+ @aruba_timeout_seconds = 600
6
+ FileUtils.touch "/tmp/test.vmdk"
7
+ end
8
+
9
+ After do
10
+ FileUtils.rm "/tmp/test.vmdk"
11
+ end
data/knife-kvm.gemspec ADDED
@@ -0,0 +1,25 @@
1
+ # -*- encoding: utf-8 -*-
2
+ $:.push File.expand_path("../lib", __FILE__)
3
+ require "knife-kvm/version"
4
+
5
+ Gem::Specification.new do |s|
6
+ s.name = "knife-kvm"
7
+ s.version = Knife::KVM::VERSION
8
+ s.has_rdoc = true
9
+ s.authors = ["Sergio Rubio"]
10
+ s.email = ["rubiojr@frameos.org","rubiojr@frameos.org"]
11
+ s.homepage = "http://github.com/rubiojr/knife-kvm"
12
+ s.summary = "KVM Support for Chef's Knife Command"
13
+ s.description = s.summary
14
+ s.extra_rdoc_files = ["README.rdoc", "LICENSE" ]
15
+
16
+ s.files = `git ls-files`.split("\n")
17
+ s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
18
+ s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
19
+ s.add_dependency "fog", ">= 1.1.1"
20
+ s.add_dependency "terminal-table"
21
+ s.add_dependency "alchemist"
22
+ s.add_dependency "chef", ">= 0.10"
23
+ s.require_paths = ["lib"]
24
+
25
+ end
@@ -0,0 +1,104 @@
1
+ #
2
+ # Author:: Sergio Rubio (<rubiojr@frameos.org>)
3
+ # Copyright:: Sergio Rubio (c) 2011
4
+ # License:: Apache License, Version 2.0
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ #
18
+
19
+ require 'chef/knife'
20
+ require 'fog'
21
+ require 'net/ssh'
22
+ require 'net/scp'
23
+ require 'alchemist'
24
+
25
+ class Chef
26
+ class Knife
27
+ module KVMBase
28
+
29
+ # :nodoc:
30
+ # Would prefer to do this in a rational way, but can't be done b/c of
31
+ # Mixlib::CLI's design :(
32
+ def self.included(includer)
33
+ includer.class_eval do
34
+
35
+ deps do
36
+ require 'net/ssh/multi'
37
+ require 'readline'
38
+ require 'chef/json_compat'
39
+ require 'terminal-table/import'
40
+ end
41
+
42
+ option :kvm_password,
43
+ :long => "--kvm-password PASSWORD",
44
+ :description => "Your KVM password",
45
+ :proc => Proc.new { |key| Chef::Config[:knife][:kvm_password] = key }
46
+
47
+ option :kvm_username,
48
+ :long => "--kvm-username USERNAME",
49
+ :default => "root",
50
+ :description => "Your KVM username (default 'root')",
51
+ :proc => Proc.new { |username| Chef::Config[:knife][:kvm_username] = (username || 'root') }
52
+
53
+ option :kvm_host,
54
+ :long => "--kvm-host ADDRESS",
55
+ :description => "Your KVM host address",
56
+ :default => "127.0.0.1",
57
+ :proc => Proc.new { |host| Chef::Config[:knife][:kvm_host] = host }
58
+ end
59
+ end
60
+
61
+ def connection
62
+ Chef::Config[:knife][:kvm_username] = 'root' if not Chef::Config[:knife][:kvm_username]
63
+ if not @connection
64
+ host = Chef::Config[:knife][:kvm_host] || '127.0.0.1'
65
+ username = Chef::Config[:knife][:kvm_username]
66
+ password = Chef::Config[:knife][:kvm_password]
67
+ libvirt_uri = ''
68
+ if host == "127.0.0.1"
69
+ libvirt_uri = "qemu+unix:///system"
70
+ else
71
+ libvirt_uri = "qemu+ssh://#{username}@#{host}/system"
72
+ end
73
+ ui.info "#{ui.color("Connecting to KVM host #{config[:kvm_host]}... ", :magenta)}"
74
+ @connection = ::Fog::Compute.new :provider => 'libvirt',
75
+ :libvirt_uri => libvirt_uri,
76
+ :libvirt_ip_command => "virt-cat -d $server_name /tmp/ip-info 2> /dev/null |grep -v 127.0.0.1"
77
+ else
78
+ @connection
79
+ end
80
+ end
81
+
82
+ def upload_file(source, dest, print_progress = true)
83
+ Net::SSH.start(config[:kvm_host], config[:kvm_username], :password => config[:kvm_password]) do |ssh|
84
+ puts "Uploading file... (#{File.basename(source)})"
85
+ ssh.scp.upload!(source, dest) do |ch, name, sent, total|
86
+ if print_progress
87
+ print "\rProgress: #{(sent.to_f * 100 / total.to_f).to_i}% completed"
88
+ end
89
+ end
90
+ end
91
+ puts if print_progress
92
+ end
93
+
94
+
95
+ def locate_config_value(key)
96
+ key = key.to_sym
97
+ Chef::Config[:knife][key] || config[key]
98
+ end
99
+
100
+ end
101
+ end
102
+ end
103
+
104
+
@@ -0,0 +1,240 @@
1
+ #
2
+ # Author:: Sergio Rubio (<rubiojr@frameos.org>)
3
+ # Copyright:: Copyright (c) 2011, Sergio Rubio
4
+ # License:: Apache License, Version 2.0
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ #
18
+
19
+ require 'chef/knife/kvm_base'
20
+
21
+ class Chef
22
+ class Knife
23
+ class KvmVmCreate < Knife
24
+
25
+ include Knife::KVMBase
26
+
27
+ deps do
28
+ require 'readline'
29
+ require 'chef/json_compat'
30
+ require 'chef/knife/bootstrap'
31
+ Chef::Knife::Bootstrap.load_deps
32
+ end
33
+
34
+ banner "knife kvm vm create (options)"
35
+
36
+ option :vm_disk,
37
+ :long => "--vm-disk FILE",
38
+ :description => "The path to the VMDK disk file"
39
+
40
+ option :vm_name,
41
+ :long => "--vm-name NAME",
42
+ :description => "The Virtual Machine name"
43
+
44
+ option :pool,
45
+ :long => "--pool NAME",
46
+ :default => 'default',
47
+ :description => "The Pool to use for the VM files (default: default)"
48
+
49
+ option :os_type,
50
+ :long => "--os-type NAME",
51
+ :default => "hvm",
52
+ :description => "The OS Type (default: hvm)"
53
+
54
+ option :memory,
55
+ :long => "--vm-memory MEM",
56
+ :default => "512",
57
+ :description => "The VM memory in MB (default: 512)"
58
+
59
+ option :chef_node_name,
60
+ :short => "-N NAME",
61
+ :long => "--node-name NAME",
62
+ :description => "The Chef node name for your new node"
63
+
64
+ option :prerelease,
65
+ :long => "--prerelease",
66
+ :description => "Install the pre-release chef gems"
67
+
68
+ option :bootstrap_version,
69
+ :long => "--bootstrap-version VERSION",
70
+ :description => "The version of Chef to install",
71
+ :proc => Proc.new { |v| Chef::Config[:knife][:bootstrap_version] = v }
72
+
73
+ option :distro,
74
+ :short => "-d DISTRO",
75
+ :long => "--distro DISTRO",
76
+ :description => "Bootstrap a distro using a template; default is 'ubuntu10.04-gems'",
77
+ :proc => Proc.new { |d| Chef::Config[:knife][:distro] = d },
78
+ :default => "ubuntu10.04-gems"
79
+
80
+ option :template_file,
81
+ :long => "--template-file TEMPLATE",
82
+ :description => "Full path to location of template to use",
83
+ :proc => Proc.new { |t| Chef::Config[:knife][:template_file] = t },
84
+ :default => false
85
+
86
+ option :run_list,
87
+ :short => "-r RUN_LIST",
88
+ :long => "--run-list RUN_LIST",
89
+ :description => "Comma separated list of roles/recipes to apply",
90
+ :proc => lambda { |o| o.split(/[\s,]+/) },
91
+ :default => []
92
+
93
+ option :ssh_user,
94
+ :short => "-x USERNAME",
95
+ :long => "--ssh-user USERNAME",
96
+ :description => "The ssh username; default is 'root'",
97
+ :default => "root"
98
+
99
+ option :ssh_password,
100
+ :short => "-P PASSWORD",
101
+ :long => "--ssh-password PASSWORD",
102
+ :description => "The ssh password"
103
+
104
+ option :identity_file,
105
+ :short => "-i IDENTITY_FILE",
106
+ :long => "--identity-file IDENTITY_FILE",
107
+ :description => "The SSH identity file used for authentication"
108
+
109
+ option :no_host_key_verify,
110
+ :long => "--no-host-key-verify",
111
+ :description => "Disable host key verification",
112
+ :boolean => true,
113
+ :default => false,
114
+ :proc => Proc.new { true }
115
+
116
+ option :network_interface,
117
+ :long => "--network-interface type:name",
118
+ :description => "The network interface description (default bridge:br0)",
119
+ :default => "bridge:br0"
120
+
121
+
122
+ def tcp_test_ssh(hostname)
123
+ tcp_socket = TCPSocket.new(hostname, 22)
124
+ readable = IO.select([tcp_socket], nil, nil, 5)
125
+ if readable
126
+ Chef::Log.debug("sshd accepting connections on #{hostname}, banner is #{tcp_socket.gets}")
127
+ yield
128
+ true
129
+ else
130
+ false
131
+ end
132
+ rescue Errno::ETIMEDOUT, Errno::EPERM
133
+ false
134
+ rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH, Errno::ENETUNREACH
135
+ sleep 2
136
+ false
137
+ ensure
138
+ tcp_socket && tcp_socket.close
139
+ end
140
+
141
+ def run
142
+ $stdout.sync = true
143
+
144
+ unless config[:vm_disk]
145
+ ui.error("You have not provided a valid VMDK file. (--vm-disk)")
146
+ exit 1
147
+ end
148
+
149
+ if not File.exist?(config[:vm_disk])
150
+ ui.error("Invalid VMDK disk file (--vm-disk)")
151
+ exit 1
152
+ end
153
+
154
+ vm_name = config[:vm_name]
155
+ if not vm_name
156
+ ui.error("Invalid Virtual Machine name (--vm-name)")
157
+ exit 1
158
+ end
159
+
160
+ pool = config[:pool]
161
+ memory = config[:memory]
162
+ vm_disk = config[:vm_disk]
163
+ os_type =config[:os_type]
164
+ destination_path = "/var/lib/libvirt/images/"
165
+
166
+ #connection.remote_command "mkdir #{destination_path}"
167
+ puts "#{ui.color("Creating VM... ", :magenta)}"
168
+ net_type, net_if = config[:network_interface].split(':')
169
+ vm = connection.servers.create :name => vm_name,
170
+ :volume_allocation => "#{File.size(vm_disk)/1024/1024}M",
171
+ :volume_capacity => '10G',
172
+ :volume_format_type => 'qcow2',
173
+ #:autostart => true, # Starting guest automatically
174
+ :volume_pool_name => pool,
175
+ :network_interface_type => net_type,
176
+ :network_bridge_name => net_if
177
+
178
+ puts "#{ui.color("Importing VM disk... ", :magenta)}"
179
+ upload_file(vm_disk, "#{destination_path}/#{vm_name}.qcow2")
180
+ vm.start
181
+
182
+ puts "#{ui.color("VM Name", :cyan)}: #{vm.name}"
183
+ puts "#{ui.color("VM Memory", :cyan)}: #{(vm.memory_size.to_f/1024/1024).round} MB"
184
+
185
+ # wait for it to be ready to do stuff
186
+ print "\n#{ui.color("Waiting server... ", :magenta)}"
187
+ timeout = 100
188
+ found = connection.servers.all.find { |v| v.name == vm.name }
189
+ loop do
190
+ begin
191
+ if not vm.addresses.nil? and not vm.addresses.empty?
192
+ puts
193
+ puts "\n#{ui.color("VM IP Address: #{vm.public_ip_address}", :cyan)}"
194
+ break
195
+ end
196
+ rescue Fog::Errors::Error
197
+ print "\r#{ui.color('Waiting a valid IP', :magenta)}..." + "." * (100 - timeout)
198
+ end
199
+ timeout -= 1
200
+ if timeout == 0
201
+ ui.error "Timeout trying to reach the VM. Couldn't find the IP address."
202
+ exit 1
203
+ end
204
+ sleep 1
205
+ found = connection.servers.all.find { |v| v.name == vm.name }
206
+ end
207
+
208
+ print "\n#{ui.color("Waiting for sshd... ", :magenta)}"
209
+ print(".") until tcp_test_ssh(vm.public_ip_address) { sleep @initial_sleep_delay ||= 10; puts(" done") }
210
+ bootstrap_for_node(vm).run
211
+
212
+ puts "\n"
213
+ puts "#{ui.color("Name", :cyan)}: #{vm.name}"
214
+ puts "#{ui.color("IP Address", :cyan)}: #{vm.public_ip_address}"
215
+ puts "#{ui.color("Environment", :cyan)}: #{config[:environment] || '_default'}"
216
+ puts "#{ui.color("Run List", :cyan)}: #{config[:run_list].join(', ')}"
217
+ puts "#{ui.color("Done!", :green)}"
218
+ end
219
+
220
+ def bootstrap_for_node(vm)
221
+ bootstrap = Chef::Knife::Bootstrap.new
222
+ bootstrap.name_args = [vm.public_ip_address]
223
+ bootstrap.config[:run_list] = config[:run_list]
224
+ bootstrap.config[:ssh_user] = config[:ssh_user]
225
+ bootstrap.config[:identity_file] = config[:identity_file]
226
+ bootstrap.config[:chef_node_name] = config[:chef_node_name] || vm.name
227
+ bootstrap.config[:bootstrap_version] = locate_config_value(:bootstrap_version)
228
+ bootstrap.config[:distro] = locate_config_value(:distro)
229
+ # bootstrap will run as root...sudo (by default) also messes up Ohai on CentOS boxes
230
+ bootstrap.config[:use_sudo] = true unless config[:ssh_user] == 'root'
231
+ bootstrap.config[:template_file] = locate_config_value(:template_file)
232
+ bootstrap.config[:environment] = config[:environment]
233
+ bootstrap.config[:no_host_key_verify] = config[:no_host_key_verify]
234
+ bootstrap.config[:ssh_password] = config[:ssh_password]
235
+ bootstrap
236
+ end
237
+
238
+ end
239
+ end
240
+ end
@@ -0,0 +1,56 @@
1
+ #
2
+ # Author:: Sergio Rubio (<rubiojr@frameos.org>)
3
+ # Copyright:: Copyright (c) 2011 Sergio Rubio
4
+ # License:: Apache License, Version 2.0
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ #
18
+
19
+ require 'chef/knife/kvm_base'
20
+
21
+ class Chef
22
+ class Knife
23
+ class KvmVmDelete < Knife
24
+
25
+ include Knife::KVMBase
26
+
27
+ banner "knife kvm vm delete VM_NAME [VM_NAME] (options)"
28
+
29
+ option :force_delete,
30
+ :long => "--force-delete NO",
31
+ :default => 'no',
32
+ :description => "Do not confirm VM deletion when yes"
33
+
34
+ def run
35
+ deleted = []
36
+ connection.servers.all.each do |vm|
37
+ @name_args.each do |vm_name|
38
+ if vm_name == vm.name
39
+ if config[:force_delete] != 'yes'
40
+ confirm("Do you really want to delete this virtual machine '#{vm.name}'")
41
+ end
42
+
43
+ vm.destroy
44
+ deleted << vm_name
45
+ ui.warn("Deleted virtual machine #{vm.name}")
46
+ end
47
+ end
48
+ end
49
+ @name_args.each do |vm_name|
50
+ ui.warn "Virtual Machine #{vm_name} not found" if not deleted.include?(vm_name)
51
+ end
52
+ end
53
+
54
+ end
55
+ end
56
+ end
@@ -0,0 +1,41 @@
1
+ #
2
+ # Author:: Sergio Rubio (<rubiojr@frameos.org>)
3
+ # Copyright:: Copyright (c) 2011 Sergio Rubio
4
+ # License:: Apache License, Version 2.0
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ #
18
+
19
+ require 'chef/knife/kvm_base'
20
+
21
+ class Chef
22
+ class Knife
23
+ class KvmVmList < Knife
24
+
25
+ include Knife::KVMBase
26
+
27
+ banner "knife kvm vm list (options)"
28
+
29
+ def run
30
+ $stdout.sync = true
31
+ vm_table = table do |t|
32
+ t.headings = %w{NAME STATE MAX_MEM CPUS OS_TYPE ARCH}
33
+ connection.servers.each do |vm|
34
+ t << [vm.name, vm.state, "#{vm.max_memory_size.to_i.kilobytes.to.megabytes.round} MB", vm.cpus, vm.os_type, vm.arch]
35
+ end
36
+ end
37
+ puts vm_table
38
+ end
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,6 @@
1
+ module Knife
2
+ module KVM
3
+ VERSION = "0.1"
4
+ MAJOR, MINOR, TINY = VERSION.split('.')
5
+ end
6
+ end
metadata ADDED
@@ -0,0 +1,106 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: knife-kvm
3
+ version: !ruby/object:Gem::Version
4
+ version: '0.1'
5
+ prerelease:
6
+ platform: ruby
7
+ authors:
8
+ - Sergio Rubio
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2011-11-30 00:00:00.000000000 Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: fog
16
+ requirement: &12667040 !ruby/object:Gem::Requirement
17
+ none: false
18
+ requirements:
19
+ - - ! '>='
20
+ - !ruby/object:Gem::Version
21
+ version: 1.1.1
22
+ type: :runtime
23
+ prerelease: false
24
+ version_requirements: *12667040
25
+ - !ruby/object:Gem::Dependency
26
+ name: terminal-table
27
+ requirement: &12666620 !ruby/object:Gem::Requirement
28
+ none: false
29
+ requirements:
30
+ - - ! '>='
31
+ - !ruby/object:Gem::Version
32
+ version: '0'
33
+ type: :runtime
34
+ prerelease: false
35
+ version_requirements: *12666620
36
+ - !ruby/object:Gem::Dependency
37
+ name: alchemist
38
+ requirement: &12666160 !ruby/object:Gem::Requirement
39
+ none: false
40
+ requirements:
41
+ - - ! '>='
42
+ - !ruby/object:Gem::Version
43
+ version: '0'
44
+ type: :runtime
45
+ prerelease: false
46
+ version_requirements: *12666160
47
+ - !ruby/object:Gem::Dependency
48
+ name: chef
49
+ requirement: &12665600 !ruby/object:Gem::Requirement
50
+ none: false
51
+ requirements:
52
+ - - ! '>='
53
+ - !ruby/object:Gem::Version
54
+ version: '0.10'
55
+ type: :runtime
56
+ prerelease: false
57
+ version_requirements: *12665600
58
+ description: KVM Support for Chef's Knife Command
59
+ email:
60
+ - rubiojr@frameos.org
61
+ - rubiojr@frameos.org
62
+ executables: []
63
+ extensions: []
64
+ extra_rdoc_files:
65
+ - README.rdoc
66
+ - LICENSE
67
+ files:
68
+ - LICENSE
69
+ - README.rdoc
70
+ - features/kvm.feature
71
+ - features/step_definitions/steps.rb
72
+ - features/support/env.rb
73
+ - knife-kvm.gemspec
74
+ - lib/chef/knife/kvm_base.rb
75
+ - lib/chef/knife/kvm_vm_create.rb
76
+ - lib/chef/knife/kvm_vm_delete.rb
77
+ - lib/chef/knife/kvm_vm_list.rb
78
+ - lib/knife-kvm/version.rb
79
+ homepage: http://github.com/rubiojr/knife-kvm
80
+ licenses: []
81
+ post_install_message:
82
+ rdoc_options: []
83
+ require_paths:
84
+ - lib
85
+ required_ruby_version: !ruby/object:Gem::Requirement
86
+ none: false
87
+ requirements:
88
+ - - ! '>='
89
+ - !ruby/object:Gem::Version
90
+ version: '0'
91
+ required_rubygems_version: !ruby/object:Gem::Requirement
92
+ none: false
93
+ requirements:
94
+ - - ! '>='
95
+ - !ruby/object:Gem::Version
96
+ version: '0'
97
+ requirements: []
98
+ rubyforge_project:
99
+ rubygems_version: 1.8.10
100
+ signing_key:
101
+ specification_version: 3
102
+ summary: KVM Support for Chef's Knife Command
103
+ test_files:
104
+ - features/kvm.feature
105
+ - features/step_definitions/steps.rb
106
+ - features/support/env.rb