Merge lp:~chiradeep/nova/msft-hyper-v-support into lp:~hudson-openstack/nova/trunk

Proposed by Chiradeep Vittal
Status: Superseded
Proposed branch: lp:~chiradeep/nova/msft-hyper-v-support
Merge into: lp:~hudson-openstack/nova/trunk
Diff against target: 700 lines (+607/-23)
5 files modified
nova/tests/hyperv_unittest.py (+67/-0)
nova/twistd.py (+16/-15)
nova/virt/connection.py (+3/-0)
nova/virt/hyperv.py (+483/-0)
nova/virt/images.py (+38/-8)
To merge this branch: bzr merge lp:~chiradeep/nova/msft-hyper-v-support
Reviewer Review Type Date Requested Status
Soren Hansen (community) Needs Fixing
Jay Pipes Pending
Review via email: mp+38301@code.launchpad.net

This proposal supersedes a proposal from 2010-10-09.

This proposal has been superseded by a proposal from 2010-10-14.

Description of the change

Introduces basic support for spawning, rebooting and destroying vms when using Microsoft Hyper-V as the hypervisor.
Images need to be in VHD format. Note that although Hyper-V doesn't accept kernel and ramdisk
separate from the image, the nova objectstore api still expects an image to have an associated aki and ari. You can use dummy aki and ari images -- the hyper-v driver won't use them or try to download them.
Requires Python's WMI module.

To post a comment you must log in.
Revision history for this message
Jay Pipes (jaypipes) wrote : Posted in a previous version of this proposal
Download full text (3.6 KiB)

Hi Chiradeep!

Thanks for the contribution and a start of Windows support in OpenStack! :)

Here are my review notes for you.

1) Documentation is sparse :)

It would be excellent to get some overall design and module documentation for your work. :) This will help those coders in the future who are maintaining and enhancing the hyper-V work. Please see Ewan Mellor's excellent documentation in the xenapi virtualization layer for an example of the kind of documentation that is helpful for maintainers.

This documentation is, IMHO, pretty critical considering the sorry state of python-wmi documentation regarding virtual environments.

Additional code comments would be very useful in places such as the following:

181 + (job, ret_val) = vs_man_svc.DefineVirtualSystem(
182 + [], None, vs_gs_data.GetText_(1))[1:]

What does vs_gs_data.GetText(1) return? What does sv_man_svc.DefineVirtualSystem() return? Without understanding these types of things, maintaining developers have zero chance of successfully fixing bugs that may occur :)

2) Please use Nova's exceptions, which are tested for in the test suites and programs, instead of generic Exception:

402 + raise Exception('instance not present %s' % instance_id)

Should be replaced with:

from nova import exception
...
raise exception.NotFound('instance not found %s' % instance_id)

same for here:

360 + if vm is None:
361 + raise Exception('instance not present %s' % instance.name)

3) Your rewrite of the _fetch_s3_image() function is good, however, it removes the efficiency of using a shared process pool in Linux/BSD environments in favour of cross-platform compatibility. It would be nice to keep the existing code and use your rewrite in an if sys.platform.startswith('win'): block.

============

And here are some style-related things to fix up...

1) Please make sure imports are ordered according to the instructions in the HACKING file. In particular, please make sure system lib imports are first, in alphabetical order, followed by a newline, then imports of 3rd-party libraries (like wmi) in alphabetical order, followed by a newline and imports of nova modules.

2) Something is amiss here:

118 +HYPERV_POWER_STATE = {
119 + 3 : power_state.SHUTDOWN,
120 + 2 : power_state.RUNNING,
121 + 32768 : power_state.PAUSED,
122 + 32768: power_state.PAUSED, # TODO
123 + 3 : power_state.CRASHED
124 +}

The indexes 3 and 32768 are doubled up.

3) Define constants for "magic numbers"

183 + if (ret_val == 4096 ): #WMI job started

Feel free to either create a constant WMI_JOB_STARTED and use that instead of the number 4096 and putting a comment at the end of the line. Self-documenting constants++ :)

Same goes for these locations:

323 + while job.JobState == 4: #job started
327 + if (job.JobState != 7): #job success
385 + if (ret_val == 4096 ): #WMI job started
442 + if (return_val == 4096 ): #WMI job started

4) This looks hacky :)

212 + vcpus = long(str(instance['vcpus']))

I recommend just:

vcpus = long(instance['vcpus'])

5) Please remove extraneous commented-out debugging stuff:

213 + #vcpus = 1

6) Python != C ;)

Please remove outer extraneous parentheses:

286 + if (ret_va...

Read more...

review: Needs Fixing
Revision history for this message
Jay Pipes (jaypipes) wrote : Posted in a previous version of this proposal

Also, I forgot to mention that we'd really need some Hyper-V specific test cases when Monty and others get around to getting our testing hardware and platform up-to-speed with Windows stuff...

Revision history for this message
Chiradeep Vittal (chiradeep) wrote : Posted in a previous version of this proposal
Download full text (5.0 KiB)

Thanks Jay. I'll put together something along the lines of the XenAPI driver.
The WMI calls are well documented on MSDN. Also, the Python WMI library generates the docstring for any WMI function that lists the parameters and return tuple.
Not sure that I want to regurgitate *all* those details in this doc, but I'll see if I can highlight some of the exemplary calls.

Some more comments below, preceded by >>>>
________________________________________
From: <email address hidden> [<email address hidden>] On Behalf Of Jay Pipes [<email address hidden>]
Sent: Monday, October 11, 2010 10:11 AM
To: <email address hidden>
Subject: Re: [Merge] lp:~chiradeep/nova/msft-hyper-v-support into lp:nova

Review: Needs Fixing
Hi Chiradeep!

Thanks for the contribution and a start of Windows support in OpenStack! :)

Here are my review notes for you.

1) Documentation is sparse :)

It would be excellent to get some overall design and module documentation for your work. :) This will help those coders in the future who are maintaining and enhancing the hyper-V work. Please see Ewan Mellor's excellent documentation in the xenapi virtualization layer for an example of the kind of documentation that is helpful for maintainers.

This documentation is, IMHO, pretty critical considering the sorry state of python-wmi documentation regarding virtual environments.

Additional code comments would be very useful in places such as the following:

181 + (job, ret_val) = vs_man_svc.DefineVirtualSystem(
182 + [], None, vs_gs_data.GetText_(1))[1:]

What does vs_gs_data.GetText(1) return? What does sv_man_svc.DefineVirtualSystem() return? Without understanding these types of things, maintaining developers have zero chance of successfully fixing bugs that may occur :)

>>>> This is simply how WMI works. When you want to pass in object references, you generate an XML representation using GetText. I think that whoever maintains this
needs a bookmark to the MSDN libraries and the PowerShell libraries. Equally someone maintaining the XenApi driver or libvirt driver needs to *get* the object model and the conventions.

2) Please use Nova's exceptions, which are tested for in the test suites and programs, instead of generic Exception:

402 + raise Exception('instance not present %s' % instance_id)

Should be replaced with:

from nova import exception
...
raise exception.NotFound('instance not found %s' % instance_id)

same for here:

360 + if vm is None:
361 + raise Exception('instance not present %s' % instance.name)

>>>> sure.

3) Your rewrite of the _fetch_s3_image() function is good, however, it removes the efficiency of using a shared process pool in Linux/BSD environments in favour of cross-platform compatibility. It would be nice to keep the existing code and use your rewrite in an if sys.platform.startswith('win'): block.

>>>> sure

============

And here are some style-related things to fix up...

1) Please make sure imports are ordered according to the instructions in the HACKING file. In particular, please make sure system lib imports are first, in alphabetical order, followed by a newline, then imports of 3rd-party libraries ...

Read more...

Revision history for this message
Jay Pipes (jaypipes) wrote : Posted in a previous version of this proposal

> Thanks Jay. I'll put together something along the lines of the XenAPI driver.
> The WMI calls are well documented on MSDN. Also, the Python WMI library
> generates the docstring for any WMI function that lists the parameters and
> return tuple.
> Not sure that I want to regurgitate *all* those details in this doc, but I'll
> see if I can highlight some of the exemplary calls.

Well, just do your best to provide a general overview of how the WMI calls are made, what's expected back from them, etc. :)

> Additional code comments would be very useful in places such as the following:
>
> 181 + (job, ret_val) = vs_man_svc.DefineVirtualSystem(
> 182 + [], None, vs_gs_data.GetText_(1))[1:]
>
> What does vs_gs_data.GetText(1) return? What does
> sv_man_svc.DefineVirtualSystem() return? Without understanding these types of
> things, maintaining developers have zero chance of successfully fixing bugs
> that may occur :)
>
> >>>> This is simply how WMI works. When you want to pass in object references,
> you generate an XML representation using GetText. I think that whoever
> maintains this
> needs a bookmark to the MSDN libraries and the PowerShell libraries. Equally
> someone maintaining the XenApi driver or libvirt driver needs to *get* the
> object model and the conventions.

I will hold off judgment about the WMI and PowerShell APIs...

If you could just put the above note in your general documentation, and even provide a couple of those links for MSDN/PowerShell docs in there, that would be great! :)

Cheers!
jay

Revision history for this message
Soren Hansen (soren) wrote :
Download full text (27.0 KiB)

On 13-10-2010 09:15, Chiradeep Vittal wrote:
> Chiradeep Vittal has proposed merging lp:~chiradeep/nova/msft-hyper-v-support into lp:nova.
>
> Requested reviews:
> Jay Pipes (jaypipes)
>
>
> Introduces basic support for spawning, rebooting and destroying vms when using Microsoft Hyper-V as the hypervisor.
> Images need to be in VHD format. Note that although Hyper-V doesn't accept kernel and ramdisk
> separate from the image, the nova objectstore api still expects an image to have an associated aki and ari. You can use dummy aki and ari images -- the hyper-v driver won't use them or try to download them.
> Requires Python's WMI module.
>

> === modified file 'nova/compute/manager.py'
> --- nova/compute/manager.py 2010-10-12 20:18:29 +0000
> +++ nova/compute/manager.py 2010-10-13 07:15:24 +0000
> @@ -39,6 +39,8 @@
> 'where instances are stored on disk')
> flags.DEFINE_string('compute_driver', 'nova.virt.connection.get_connection',
> 'Driver to use for volume creation')
> +flags.DEFINE_string('images_path', utils.abspath('../images'),
> + 'path to decrypted local images if not using s3')

Each flag must only be defined once. images_path is also defined in
nova.objectstore.images. Either import that or move the flag to a common
place and import that.

> === modified file 'nova/virt/connection.py'
> --- nova/virt/connection.py 2010-08-30 13:19:14 +0000
> +++ nova/virt/connection.py 2010-10-13 07:15:24 +0000
> @@ -26,6 +26,7 @@
> from nova.virt import fake
> from nova.virt import libvirt_conn
> from nova.virt import xenapi
> +from nova.virt import hyperv
>
>
> FLAGS = flags.FLAGS
> @@ -49,6 +50,8 @@
> conn = libvirt_conn.get_connection(read_only)
> elif t == 'xenapi':
> conn = xenapi.get_connection(read_only)
> + elif t == 'hyperv':
> + conn = hyperv.get_connection(read_only)
> else:
> raise Exception('Unknown connection type "%s"' % t)
>
>

This is troublesome. We have no python-wmi on linux, and unconditionally
importing the hyperv driver means unconditionally importing wmi which
fails spectacularly.

nova.virt.connection.get_connection should probably be refactored to use
nova.utils.import_object or similar, based on the defined
connection_type. That would solve this problem.

> === added file 'nova/virt/hyperv.py'
> --- nova/virt/hyperv.py 1970-01-01 00:00:00 +0000
> +++ nova/virt/hyperv.py 2010-10-13 07:15:24 +0000
> @@ -0,0 +1,453 @@
> +# vim: tabstop=4 shiftwidth=4 softtabstop=4
> +
> +# Copyright (c) 2010 Cloud.com, Inc
> +#
> +# 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 L...

review: Needs Fixing
Revision history for this message
Jay Pipes (jaypipes) wrote :

Hi again, Chiradeep :) Thanks much for addressing the documentation concerns and the style issues on the first review! I second Soren's suggestions/fixups.

Revision history for this message
Chiradeep Vittal (chiradeep) wrote :
Download full text (28.5 KiB)

For the "import wmi" issue, I propose adopting the solution used in the xenapi
driver (use __import__).
I can raise a bug to get this fixed in the manner suggested by Soren.

Regarding long-running blocking operations (fetch image / start vm), I am not yet
familiar with the Twisted framework. I propose that we leave these as is and raise
bugs to fix later.

New exceptions: did you mean add one into nova/exception.py or add a new one
inside hyperv.py. I've added a couple in the latter.

Unit tests: I've added a unit test (hyperv_unittest.py). The unit test framework, I think
assumes that the controller and the driver are on the same host. I haven't managed
to port the entire controller to Windows (only the compute manager). There is a
dependency on where redis runs), so I haven't integrated it into the test case framework.
I am also not sure on how to make it conditional (on Linux) within the test case framework.

________________________________________
From: <email address hidden> [<email address hidden>] On Behalf Of Soren Hansen [<email address hidden>]
Sent: Wednesday, October 13, 2010 3:52 AM
To: <email address hidden>
Subject: Re: [Merge] lp:~chiradeep/nova/msft-hyper-v-support into lp:nova

Review: Needs Fixing
On 13-10-2010 09:15, Chiradeep Vittal wrote:
> Chiradeep Vittal has proposed merging lp:~chiradeep/nova/msft-hyper-v-support into lp:nova.
>
> Requested reviews:
> Jay Pipes (jaypipes)
>
>
> Introduces basic support for spawning, rebooting and destroying vms when using Microsoft Hyper-V as the hypervisor.
> Images need to be in VHD format. Note that although Hyper-V doesn't accept kernel and ramdisk
> separate from the image, the nova objectstore api still expects an image to have an associated aki and ari. You can use dummy aki and ari images -- the hyper-v driver won't use them or try to download them.
> Requires Python's WMI module.
>

> === modified file 'nova/compute/manager.py'
> --- nova/compute/manager.py 2010-10-12 20:18:29 +0000
> +++ nova/compute/manager.py 2010-10-13 07:15:24 +0000
> @@ -39,6 +39,8 @@
> 'where instances are stored on disk')
> flags.DEFINE_string('compute_driver', 'nova.virt.connection.get_connection',
> 'Driver to use for volume creation')
> +flags.DEFINE_string('images_path', utils.abspath('../images'),
> + 'path to decrypted local images if not using s3')

Each flag must only be defined once. images_path is also defined in
nova.objectstore.images. Either import that or move the flag to a common
place and import that.

>>>> fixed by reverting.

> === modified file 'nova/virt/connection.py'
> --- nova/virt/connection.py 2010-08-30 13:19:14 +0000
> +++ nova/virt/connection.py 2010-10-13 07:15:24 +0000
> @@ -26,6 +26,7 @@
> from nova.virt import fake
> from nova.virt import libvirt_conn
> from nova.virt import xenapi
> +from nova.virt import hyperv
>
>
> FLAGS = flags.FLAGS
> @@ -49,6 +50,8 @@
> conn = libvirt_conn.get_connection(read_only)
> elif t == 'xenapi':
> conn = xenapi.get_connection(read_only)
> + elif t == 'hyperv':
> + conn = hyperv.get_connection(read_only)
> else:
> ...

344. By Chiradeep Vittal <chiradeep@chiradeep-lt2>

Added a unit test but not integrated it

345. By Chiradeep Vittal <chiradeep@chiradeep-lt2>

review comments

346. By Chiradeep Vittal <chiradeep@chiradeep-lt2>

fix indent

347. By Chiradeep Vittal <chiradeep@chiradeep-lt2>

revert to generic exceptions

348. By Chiradeep Vittal <chiradeep@chiradeep-lt2>

remove nonexistent exception

349. By Chiradeep Vittal <chiradeep@chiradeep-lt2>

Merged from trunk and fixed merge issues.
Also fixed pep8 issues

350. By Chiradeep Vittal <chiradeep@chiradeep-lt2>

remove some logging

351. By Chiradeep Vittal <chiradeep@chiradeep-lt2>

Merge from trunk: process replaced with util

352. By Chiradeep Vittal <chiradeep@chiradeep-lt2>

Merge from trunk: process replaced with util

353. By Chiradeep Vittal <chiradeep@chiradeep-lt2>

Merge from trunk again -- get rid of twistd dependencies

354. By Chiradeep Vittal <chiradeep@chiradeep-lt2>

i18n logging and exception strings

355. By Chiradeep Vittal <chiradeep@chiradeep-lt2>

Merge from trunk again

356. By Chiradeep Vittal <chiradeep@chiradeep-lt2>

Revert some unneeded formatting since twistd is no longer used

357. By Chiradeep Vittal <chiradeep@chiradeep-lt2>

Redis dependency no longer needed

358. By Chiradeep Vittal <chiradeep@chiradeep-lt2>

need one more newline

359. By Chiradeep Vittal

Make test case work again

360. By Chiradeep Vittal

Add to Authors and mailmap

Unmerged revisions

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1=== added file 'nova/tests/hyperv_unittest.py'
2--- nova/tests/hyperv_unittest.py 1970-01-01 00:00:00 +0000
3+++ nova/tests/hyperv_unittest.py 2010-10-14 06:23:40 +0000
4@@ -0,0 +1,67 @@
5+# vim: tabstop=4 shiftwidth=4 softtabstop=4
6+#
7+# Copyright 2010 Cloud.com, Inc
8+#
9+# Licensed under the Apache License, Version 2.0 (the "License"); you may
10+# not use this file except in compliance with the License. You may obtain
11+# a copy of the License at
12+#
13+# http://www.apache.org/licenses/LICENSE-2.0
14+#
15+# Unless required by applicable law or agreed to in writing, software
16+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
17+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
18+# License for the specific language governing permissions and limitations
19+# under the License.
20+"""
21+Tests For Hyper-V driver
22+"""
23+
24+import random
25+
26+from nova import db
27+from nova import flags
28+from nova import test
29+
30+from nova.virt import hyperv
31+
32+FLAGS = flags.FLAGS
33+FLAGS.connection_type = 'hyperv'
34+# Redis is probably not running on Hyper-V host.
35+# Change this to the actual Redis host
36+FLAGS.redis_host = '127.0.0.1'
37+
38+
39+class HyperVTestCase(test.TrialTestCase):
40+ """Test cases for the Hyper-V driver"""
41+ def setUp(self): # pylint: disable-msg=C0103
42+ pass
43+
44+ def test_create_destroy(self):
45+ """Create a VM and destroy it"""
46+ instance = {'internal_id' : random.randint(1, 1000000),
47+ 'memory_mb' : '1024',
48+ 'mac_address' : '02:12:34:46:56:67',
49+ 'vcpus' : 2,
50+ 'project_id' : 'fake',
51+ 'instance_type' : 'm1.small'}
52+
53+ instance_ref = db.instance_create(None, instance)
54+
55+ conn = hyperv.get_connection(False)
56+ conn._create_vm(instance_ref) # pylint: disable-msg=W0212
57+ found = [n for n in conn.list_instances()
58+ if n == instance_ref['name']]
59+ self.assertTrue(len(found) == 1)
60+ info = conn.get_info(instance_ref['name'])
61+ #Unfortunately since the vm is not running at this point,
62+ #we cannot obtain memory information from get_info
63+ self.assertEquals(info['num_cpu'], instance_ref['vcpus'])
64+
65+ conn.destroy(instance_ref)
66+ found = [n for n in conn.list_instances()
67+ if n == instance_ref['name']]
68+ self.assertTrue(len(found) == 0)
69+
70+ def tearDown(self): # pylint: disable-msg=C0103
71+ pass
72
73=== modified file 'nova/twistd.py'
74--- nova/twistd.py 2010-08-17 22:05:06 +0000
75+++ nova/twistd.py 2010-10-14 06:23:40 +0000
76@@ -224,21 +224,22 @@
77 logging.getLogger('amqplib').setLevel(logging.WARN)
78 FLAGS.python = filename
79 FLAGS.no_save = True
80- if not FLAGS.pidfile:
81- FLAGS.pidfile = '%s.pid' % name
82- elif FLAGS.pidfile.endswith('twistd.pid'):
83- FLAGS.pidfile = FLAGS.pidfile.replace('twistd.pid', '%s.pid' % name)
84- # NOTE(vish): if we're running nodaemon, redirect the log to stdout
85- if FLAGS.nodaemon and not FLAGS.logfile:
86- FLAGS.logfile = "-"
87- if not FLAGS.logfile:
88- FLAGS.logfile = '%s.log' % name
89- elif FLAGS.logfile.endswith('twistd.log'):
90- FLAGS.logfile = FLAGS.logfile.replace('twistd.log', '%s.log' % name)
91- if not FLAGS.prefix:
92- FLAGS.prefix = name
93- elif FLAGS.prefix.endswith('twisted'):
94- FLAGS.prefix = FLAGS.prefix.replace('twisted', name)
95+ if sys.platform != 'win32':
96+ if not FLAGS.pidfile:
97+ FLAGS.pidfile = '%s.pid' % name
98+ elif FLAGS.pidfile.endswith('twistd.pid'):
99+ FLAGS.pidfile = FLAGS.pidfile.replace('twistd.pid', '%s.pid' % name)
100+ # NOTE(vish): if we're running nodaemon, redirect the log to stdout
101+ if FLAGS.nodaemon and not FLAGS.logfile:
102+ FLAGS.logfile = "-"
103+ if not FLAGS.logfile:
104+ FLAGS.logfile = '%s.log' % name
105+ elif FLAGS.logfile.endswith('twistd.log'):
106+ FLAGS.logfile = FLAGS.logfile.replace('twistd.log', '%s.log' % name)
107+ if not FLAGS.prefix:
108+ FLAGS.prefix = name
109+ elif FLAGS.prefix.endswith('twisted'):
110+ FLAGS.prefix = FLAGS.prefix.replace('twisted', name)
111
112 action = 'start'
113 if len(argv) > 1:
114
115=== modified file 'nova/virt/connection.py'
116--- nova/virt/connection.py 2010-08-30 13:19:14 +0000
117+++ nova/virt/connection.py 2010-10-14 06:23:40 +0000
118@@ -26,6 +26,7 @@
119 from nova.virt import fake
120 from nova.virt import libvirt_conn
121 from nova.virt import xenapi
122+from nova.virt import hyperv
123
124
125 FLAGS = flags.FLAGS
126@@ -49,6 +50,8 @@
127 conn = libvirt_conn.get_connection(read_only)
128 elif t == 'xenapi':
129 conn = xenapi.get_connection(read_only)
130+ elif t == 'hyperv':
131+ conn = hyperv.get_connection(read_only)
132 else:
133 raise Exception('Unknown connection type "%s"' % t)
134
135
136=== added file 'nova/virt/hyperv.py'
137--- nova/virt/hyperv.py 1970-01-01 00:00:00 +0000
138+++ nova/virt/hyperv.py 2010-10-14 06:23:40 +0000
139@@ -0,0 +1,483 @@
140+# vim: tabstop=4 shiftwidth=4 softtabstop=4
141+
142+# Copyright (c) 2010 Cloud.com, Inc
143+#
144+# Licensed under the Apache License, Version 2.0 (the "License"); you may
145+# not use this file except in compliance with the License. You may obtain
146+# a copy of the License at
147+#
148+# http://www.apache.org/licenses/LICENSE-2.0
149+#
150+# Unless required by applicable law or agreed to in writing, software
151+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
152+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
153+# License for the specific language governing permissions and limitations
154+# under the License.
155+
156+"""
157+A connection to Hyper-V .
158+Uses Windows Management Instrumentation (WMI) calls to interact with Hyper-V
159+Hyper-V WMI usage:
160+ http://msdn.microsoft.com/en-us/library/cc723875%28v=VS.85%29.aspx
161+The Hyper-V object model briefly:
162+ The physical computer and its hosted virtual machines are each represented
163+ by the Msvm_ComputerSystem class.
164+
165+ Each virtual machine is associated with a
166+ Msvm_VirtualSystemGlobalSettingData (vs_gs_data) instance and one or more
167+ Msvm_VirtualSystemSettingData (vmsetting) instances. For each vmsetting
168+ there is a series of Msvm_ResourceAllocationSettingData (rasd) objects.
169+ The rasd objects describe the settings for each device in a VM.
170+ Together, the vs_gs_data, vmsettings and rasds describe the configuration
171+ of the virtual machine.
172+
173+ Creating new resources such as disks and nics involves cloning a default
174+ rasd object and appropriately modifying the clone and calling the
175+ AddVirtualSystemResources WMI method
176+ Changing resources such as memory uses the ModifyVirtualSystemResources
177+ WMI method
178+
179+Using the Python WMI library:
180+ Tutorial:
181+ http://timgolden.me.uk/python/wmi/tutorial.html
182+ Hyper-V WMI objects can be retrieved simply by using the class name
183+ of the WMI object and optionally specifying a column to filter the
184+ result set. More complex filters can be formed using WQL (sql-like)
185+ queries.
186+ The parameters and return tuples of WMI method calls can gleaned by
187+ examining the doc string. For example:
188+ >>> vs_man_svc.ModifyVirtualSystemResources.__doc__
189+ ModifyVirtualSystemResources (ComputerSystem, ResourceSettingData[])
190+ => (Job, ReturnValue)'
191+ When passing setting data (ResourceSettingData) to the WMI method,
192+ an XML representation of the data is passed in using GetText_(1).
193+ Available methods on a service can be determined using method.keys():
194+ >>> vs_man_svc.methods.keys()
195+ vmsettings and rasds for a vm can be retrieved using the 'associators'
196+ method with the appropriate return class.
197+ Long running WMI commands generally return a Job (an instance of
198+ Msvm_ConcreteJob) whose state can be polled to determine when it finishes
199+
200+"""
201+
202+import os
203+import logging
204+import time
205+
206+from twisted.internet import defer
207+
208+from nova import exception
209+from nova import flags
210+from nova.auth import manager
211+from nova.compute import power_state
212+from nova.virt import images
213+
214+wmi = None
215+
216+
217+FLAGS = flags.FLAGS
218+
219+
220+HYPERV_POWER_STATE = {
221+ 3 : power_state.SHUTDOWN,
222+ 2 : power_state.RUNNING,
223+ 32768 : power_state.PAUSED,
224+}
225+
226+
227+REQ_POWER_STATE = {
228+ 'Enabled' : 2,
229+ 'Disabled': 3,
230+ 'Reboot' : 10,
231+ 'Reset' : 11,
232+ 'Paused' : 32768,
233+ 'Suspended': 32769
234+}
235+
236+
237+WMI_JOB_STATUS_STARTED = 4096
238+WMI_JOB_STATE_RUNNING = 4
239+WMI_JOB_STATE_COMPLETED = 7
240+
241+##### Exceptions
242+
243+
244+class HyperVError(Exception):
245+ """Base Exception class for all hyper-v errors."""
246+ def __init__(self, *args):
247+ Exception.__init__(self, *args)
248+
249+
250+class VmResourceAllocationError(HyperVError):
251+ """Raised when Hyper-V is unable to create or add a resource to
252+ a VM
253+ """
254+ def __init__(self, *args):
255+ HyperVError.__init__(self, *args)
256+
257+
258+class VmOperationError(HyperVError):
259+ """Raised when Hyper-V is unable to change the state of
260+ a VM (start/stop/reboot/destroy)
261+ """
262+ def __init__(self, *args):
263+ HyperVError.__init__(self, *args)
264+
265+
266+def get_connection(_):
267+ global wmi
268+ if wmi is None:
269+ wmi = __import__('wmi')
270+ return HyperVConnection()
271+
272+
273+class HyperVConnection(object):
274+ def __init__(self):
275+ self._conn = wmi.WMI(moniker='//./root/virtualization')
276+ self._cim_conn = wmi.WMI(moniker='//./root/cimv2')
277+
278+ def list_instances(self):
279+ """ Return the names of all the instances known to Hyper-V. """
280+ vms = [v.ElementName \
281+ for v in self._conn.Msvm_ComputerSystem(['ElementName'])]
282+ return vms
283+
284+ @defer.inlineCallbacks
285+ def spawn(self, instance):
286+ """ Create a new VM and start it."""
287+ vm = yield self._lookup(instance.name)
288+ if vm is not None:
289+ raise exception.Duplicate('Attempted to create duplicate name %s' %
290+ instance.name)
291+
292+ user = manager.AuthManager().get_user(instance['user_id'])
293+ project = manager.AuthManager().get_project(instance['project_id'])
294+ #Fetch the file, assume it is a VHD file.
295+ base_vhd_filename = os.path.join(FLAGS.instances_path,
296+ instance['str_id'])
297+ vhdfile = "%s.vhd" % (base_vhd_filename)
298+ yield images.fetch(instance['image_id'], vhdfile, user, project)
299+
300+ try:
301+ yield self._create_vm(instance)
302+
303+ yield self._create_disk(instance['name'], vhdfile)
304+ yield self._create_nic(instance['name'], instance['mac_address'])
305+
306+ logging.debug('Starting VM %s ', instance.name)
307+ yield self._set_vm_state(instance['name'], 'Enabled')
308+ logging.info('Started VM %s ', instance.name)
309+ except Exception as exn:
310+ logging.error('spawn vm failed: %s', exn)
311+ self.destroy(instance)
312+
313+ def _create_vm(self, instance):
314+ """Create a VM but don't start it. """
315+ vs_man_svc = self._conn.Msvm_VirtualSystemManagementService()[0]
316+
317+ vs_gs_data = self._conn.Msvm_VirtualSystemGlobalSettingData.new()
318+ vs_gs_data.ElementName = instance['name']
319+ (job, ret_val) = vs_man_svc.DefineVirtualSystem(
320+ [], None, vs_gs_data.GetText_(1))[1:]
321+ if ret_val == WMI_JOB_STATUS_STARTED:
322+ success = self._check_job_status(job)
323+ else:
324+ success = (ret_val == 0)
325+
326+ if not success:
327+ raise VmResourceAllocationException('Failed to create VM %s',
328+ instance.name)
329+
330+ logging.debug('Created VM %s...', instance.name)
331+ vm = self._conn.Msvm_ComputerSystem(ElementName=instance.name)[0]
332+
333+ vmsettings = vm.associators(
334+ wmi_result_class='Msvm_VirtualSystemSettingData')
335+ vmsetting = [s for s in vmsettings
336+ if s.SettingType == 3][0] # avoid snapshots
337+ memsetting = vmsetting.associators(wmi_result_class=
338+ 'Msvm_MemorySettingData')[0]
339+ #No Dynamic Memory, so reservation, limit and quantity are identical.
340+ mem = long(str(instance['memory_mb']))
341+ memsetting.VirtualQuantity = mem
342+ memsetting.Reservation = mem
343+ memsetting.Limit = mem
344+
345+ (job, ret_val) = vs_man_svc.ModifyVirtualSystemResources(
346+ vm.path_(), [memsetting.GetText_(1)])
347+ logging.debug('Set memory for vm %s...', instance.name)
348+ procsetting = vmsetting.associators(wmi_result_class=
349+ 'Msvm_ProcessorSettingData')[0]
350+ vcpus = long(instance['vcpus'])
351+ procsetting.VirtualQuantity = vcpus
352+ procsetting.Reservation = vcpus
353+ procsetting.Limit = vcpus
354+
355+ (job, ret_val) = vs_man_svc.ModifyVirtualSystemResources(
356+ vm.path_(), [procsetting.GetText_(1)])
357+ logging.debug('Set vcpus for vm %s...', instance.name)
358+
359+ def _create_disk(self, vm_name, vhdfile):
360+ """Create a disk and attach it to the vm"""
361+ logging.debug("Creating disk for %s by attaching disk file %s",
362+ vm_name, vhdfile)
363+ #Find the IDE controller for the vm.
364+ vms = self._conn.MSVM_ComputerSystem(ElementName=vm_name)
365+ vm = vms[0]
366+ vmsettings = vm.associators(
367+ wmi_result_class='Msvm_VirtualSystemSettingData')
368+ rasds = vmsettings[0].associators(
369+ wmi_result_class='MSVM_ResourceAllocationSettingData')
370+ ctrller = [r for r in rasds
371+ if r.ResourceSubType == 'Microsoft Emulated IDE Controller'\
372+ and r.Address == "0"]
373+ #Find the default disk drive object for the vm and clone it.
374+ diskdflt = self._conn.query(
375+ "SELECT * FROM Msvm_ResourceAllocationSettingData \
376+ WHERE ResourceSubType LIKE 'Microsoft Synthetic Disk Drive'\
377+ AND InstanceID LIKE '%Default%'")[0]
378+ diskdrive = self._clone_wmi_obj(
379+ 'Msvm_ResourceAllocationSettingData', diskdflt)
380+ #Set the IDE ctrller as parent.
381+ diskdrive.Parent = ctrller[0].path_()
382+ diskdrive.Address = 0
383+ #Add the cloned disk drive object to the vm.
384+ new_resources = self._add_virt_resource(diskdrive, vm)
385+ if new_resources is None:
386+ raise VmResourceAllocationError('Failed to add diskdrive to VM %s',
387+ vm_name)
388+ diskdrive_path = new_resources[0]
389+ logging.debug("New disk drive path is %s", diskdrive_path)
390+ #Find the default VHD disk object.
391+ vhddefault = self._conn.query(
392+ "SELECT * FROM Msvm_ResourceAllocationSettingData \
393+ WHERE ResourceSubType LIKE 'Microsoft Virtual Hard Disk' AND \
394+ InstanceID LIKE '%Default%' ")[0]
395+
396+ #Clone the default and point it to the image file.
397+ vhddisk = self._clone_wmi_obj(
398+ 'Msvm_ResourceAllocationSettingData', vhddefault)
399+ #Set the new drive as the parent.
400+ vhddisk.Parent = diskdrive_path
401+ vhddisk.Connection = [vhdfile]
402+
403+ #Add the new vhd object as a virtual hard disk to the vm.
404+ new_resources = self._add_virt_resource(vhddisk, vm)
405+ if new_resources is None:
406+ raise VmResourceAllocationError('Failed to add vhd file to VM %s',
407+ vm_name)
408+ logging.info("Created disk for %s ", vm_name)
409+
410+ def _create_nic(self, vm_name, mac):
411+ """Create a (emulated) nic and attach it to the vm"""
412+ logging.debug("Creating nic for %s ", vm_name)
413+ #Find the vswitch that is connected to the physical nic.
414+ vms = self._conn.Msvm_ComputerSystem(ElementName=vm_name)
415+ extswitch = self._find_external_network()
416+ vm = vms[0]
417+ switch_svc = self._conn.Msvm_VirtualSwitchManagementService()[0]
418+ #Find the default nic and clone it to create a new nic for the vm.
419+ #Use Msvm_SyntheticEthernetPortSettingData for Windows or Linux with
420+ #Linux Integration Components installed.
421+ emulatednics_data = self._conn.Msvm_EmulatedEthernetPortSettingData()
422+ default_nic_data = [n for n in emulatednics_data
423+ if n.InstanceID.rfind('Default') > 0]
424+ new_nic_data = self._clone_wmi_obj(
425+ 'Msvm_EmulatedEthernetPortSettingData',
426+ default_nic_data[0])
427+ #Create a port on the vswitch.
428+ (new_port, ret_val) = switch_svc.CreateSwitchPort(vm_name, vm_name,
429+ "", extswitch.path_())
430+ if ret_val != 0:
431+ logging.error("Failed creating a new port on the external vswitch")
432+ raise VmResourceAllocationError('Failed creating port for %s',
433+ vm_name)
434+ logging.debug("Created switch port %s on switch %s",
435+ vm_name, extswitch.path_())
436+ #Connect the new nic to the new port.
437+ new_nic_data.Connection = [new_port]
438+ new_nic_data.ElementName = vm_name + ' nic'
439+ new_nic_data.Address = ''.join(mac.split(':'))
440+ new_nic_data.StaticMacAddress = 'TRUE'
441+ #Add the new nic to the vm.
442+ new_resources = self._add_virt_resource(new_nic_data, vm)
443+ if new_resources is None:
444+ raise VmResourceAllocationError('Failed to add nic to VM %s',
445+ vm_name)
446+ logging.info("Created nic for %s ", vm_name)
447+
448+ def _add_virt_resource(self, res_setting_data, target_vm):
449+ """Add a new resource (disk/nic) to the VM"""
450+ vs_man_svc = self._conn.Msvm_VirtualSystemManagementService()[0]
451+ (job, new_resources, ret_val) = vs_man_svc.\
452+ AddVirtualSystemResources([res_setting_data.GetText_(1)],
453+ target_vm.path_())
454+ success = True
455+ if ret_val == WMI_JOB_STATUS_STARTED:
456+ success = self._check_job_status(job)
457+ else:
458+ success = (ret_val == 0)
459+ if success:
460+ return new_resources
461+ else:
462+ return None
463+
464+ #TODO: use the reactor to poll instead of sleep
465+ def _check_job_status(self, jobpath):
466+ """Poll WMI job state for completion"""
467+ #Jobs have a path of the form:
468+ #\\WIN-P5IG7367DAG\root\virtualization:Msvm_ConcreteJob.InstanceID="8A496B9C-AF4D-4E98-BD3C-1128CD85320D"
469+ inst_id = jobpath.split(':')[1].split('=')[1].strip('\"')
470+ jobs = self._conn.Msvm_ConcreteJob(InstanceID=inst_id)
471+ if len(jobs) == 0:
472+ return False
473+ job = jobs[0]
474+ while job.JobState == WMI_JOB_STATE_RUNNING:
475+ time.sleep(0.1)
476+ job = self._conn.Msvm_ConcreteJob(InstanceID=inst_id)[0]
477+ if job.JobState != WMI_JOB_STATE_COMPLETED:
478+ logging.debug("WMI job failed: %s", job.ErrorSummaryDescription)
479+ return False
480+ logging.debug("WMI job succeeded: %s, Elapsed=%s ", job.Description,
481+ job.ElapsedTime)
482+ return True
483+
484+ def _find_external_network(self):
485+ """Find the vswitch that is connected to the physical nic.
486+ Assumes only one physical nic on the host
487+ """
488+ #If there are no physical nics connected to networks, return.
489+ bound = self._conn.Msvm_ExternalEthernetPort(IsBound='TRUE')
490+ if len(bound) == 0:
491+ return None
492+ return self._conn.Msvm_ExternalEthernetPort(IsBound='TRUE')[0]\
493+ .associators(wmi_result_class='Msvm_SwitchLANEndpoint')[0]\
494+ .associators(wmi_result_class='Msvm_SwitchPort')[0]\
495+ .associators(wmi_result_class='Msvm_VirtualSwitch')[0]
496+
497+ def _clone_wmi_obj(self, wmi_class, wmi_obj):
498+ """Clone a WMI object"""
499+ cl = self._conn.__getattr__(wmi_class) # get the class
500+ newinst = cl.new()
501+ #Copy the properties from the original.
502+ for prop in wmi_obj._properties:
503+ newinst.Properties_.Item(prop).Value =\
504+ wmi_obj.Properties_.Item(prop).Value
505+ return newinst
506+
507+ @defer.inlineCallbacks
508+ def reboot(self, instance):
509+ """Reboot the specified instance."""
510+ vm = yield self._lookup(instance.name)
511+ if vm is None:
512+ raise exception.NotFound('instance not present %s' % instance.name)
513+ self._set_vm_state(instance.name, 'Reboot')
514+
515+ @defer.inlineCallbacks
516+ def destroy(self, instance):
517+ """Destroy the VM. Also destroy the associated VHD disk files"""
518+ logging.debug("Got request to destroy vm %s", instance.name)
519+ vm = yield self._lookup(instance.name)
520+ if vm is None:
521+ defer.returnValue(None)
522+ vm = self._conn.Msvm_ComputerSystem(ElementName=instance.name)[0]
523+ vs_man_svc = self._conn.Msvm_VirtualSystemManagementService()[0]
524+ #Stop the VM first.
525+ self._set_vm_state(instance.name, 'Disabled')
526+ vmsettings = vm.associators(wmi_result_class=
527+ 'Msvm_VirtualSystemSettingData')
528+ rasds = vmsettings[0].associators(wmi_result_class=
529+ 'MSVM_ResourceAllocationSettingData')
530+ disks = [r for r in rasds \
531+ if r.ResourceSubType == 'Microsoft Virtual Hard Disk']
532+ diskfiles = []
533+ #Collect disk file information before destroying the VM.
534+ for disk in disks:
535+ diskfiles.extend([c for c in disk.Connection])
536+ #Nuke the VM. Does not destroy disks.
537+ (job, ret_val) = vs_man_svc.DestroyVirtualSystem(vm.path_())
538+ if ret_val == WMI_JOB_STATUS_STARTED:
539+ success = self._check_job_status(job)
540+ elif ret_val == 0:
541+ success = True
542+ if not success:
543+ raise VmOperationError('Failed to destroy vm %s' % instance.name)
544+ #Delete associated vhd disk files.
545+ for disk in diskfiles:
546+ vhdfile = self._cim_conn.CIM_DataFile(Name=disk)
547+ for vf in vhdfile:
548+ vf.Delete()
549+ logging.debug("Deleted disk %s vm %s", vhdfile, instance.name)
550+
551+ def get_info(self, instance_id):
552+ """Get information about the VM"""
553+ vm = self._lookup(instance_id)
554+ if vm is None:
555+ raise exception.NotFound('instance not present %s' % instance_id)
556+ vm = self._conn.Msvm_ComputerSystem(ElementName=instance_id)[0]
557+ vs_man_svc = self._conn.Msvm_VirtualSystemManagementService()[0]
558+ vmsettings = vm.associators(wmi_result_class=
559+ 'Msvm_VirtualSystemSettingData')
560+ settings_paths = [v.path_() for v in vmsettings]
561+ #See http://msdn.microsoft.com/en-us/library/cc160706%28VS.85%29.aspx
562+ summary_info = vs_man_svc.GetSummaryInformation(
563+ [4, 100, 103, 105], settings_paths)[1]
564+ info = summary_info[0]
565+ logging.debug("Got Info for vm %s: state=%s, mem=%s, num_cpu=%s, \
566+ cpu_time=%s", instance_id,
567+ str(HYPERV_POWER_STATE[info.EnabledState]),
568+ str(info.MemoryUsage),
569+ str(info.NumberOfProcessors),
570+ str(info.UpTime))
571+
572+ return {'state': HYPERV_POWER_STATE[info.EnabledState],
573+ 'max_mem': info.MemoryUsage,
574+ 'mem': info.MemoryUsage,
575+ 'num_cpu': info.NumberOfProcessors,
576+ 'cpu_time': info.UpTime}
577+
578+ def _lookup(self, i):
579+ vms = self._conn.Msvm_ComputerSystem(ElementName=i)
580+ n = len(vms)
581+ if n == 0:
582+ return None
583+ elif n > 1:
584+ raise Exception('duplicate name found: %s' % i)
585+ else:
586+ return vms[0].ElementName
587+
588+ def _set_vm_state(self, vm_name, req_state):
589+ """Set the desired state of the VM"""
590+ vms = self._conn.Msvm_ComputerSystem(ElementName=vm_name)
591+ if len(vms) == 0:
592+ return False
593+ (job, ret_val) = vms[0].RequestStateChange(REQ_POWER_STATE[req_state])
594+ success = False
595+ if ret_val == WMI_JOB_STATUS_STARTED:
596+ success = self._check_job_status(job)
597+ elif ret_val == 0:
598+ success = True
599+ elif ret_val == 32775:
600+ #Invalid state for current operation. Typically means it is
601+ #already in the state requested
602+ success = True
603+ if success:
604+ logging.info("Successfully changed vm state of %s to %s",
605+ vm_name, req_state)
606+ else:
607+ logging.error("Failed to change vm state of %s to %s",
608+ vm_name, req_state)
609+ raise VmOperationError("Failed to change vm state of %s to %s",
610+ vm_name, req_state)
611+
612+ def attach_volume(self, instance_name, device_path, mountpoint):
613+ vm = self._lookup(instance_name)
614+ if vm is None:
615+ raise exception.NotFound('Cannot attach volume to missing %s vm' %
616+ instance_name)
617+
618+ def detach_volume(self, instance_name, mountpoint):
619+ vm = self._lookup(instance_name)
620+ if vm is None:
621+ raise exception.NotFound('Cannot detach volume from missing %s ' %
622+ instance_name)
623
624=== modified file 'nova/virt/images.py'
625--- nova/virt/images.py 2010-10-07 14:03:43 +0000
626+++ nova/virt/images.py 2010-10-14 06:23:40 +0000
627@@ -21,8 +21,12 @@
628 Handling of VM disk images.
629 """
630
631+import logging
632 import os.path
633+import shutil
634+import sys
635 import time
636+import urllib2
637 import urlparse
638
639 from nova import flags
640@@ -45,8 +49,28 @@
641 return f(image, path, user, project)
642
643
644+def _fetch_image_no_curl(url, path, headers):
645+ request = urllib2.Request(url)
646+ for (k, v) in headers.iteritems():
647+ request.add_header(k, v)
648+
649+ def urlretrieve(urlfile, fpath):
650+ chunk = 1 * 1024 * 1024
651+ f = open(fpath, "wb")
652+ while 1:
653+ data = urlfile.read(chunk)
654+ if not data:
655+ break
656+ f.write(data)
657+
658+ urlopened = urllib2.urlopen(request)
659+ urlretrieve(urlopened, path)
660+ logging.debug("Finished retreving %s -- placed in %s", url, path)
661+
662+
663 def _fetch_s3_image(image, path, user, project):
664 url = image_url(image)
665+ logging.debug("About to retrieve %s and place it in %s", url, path)
666
667 # This should probably move somewhere else, like e.g. a download_as
668 # method on User objects and at the same time get rewritten to use
669@@ -61,17 +85,23 @@
670 url_path)
671 headers['Authorization'] = 'AWS %s:%s' % (access, signature)
672
673- cmd = ['/usr/bin/curl', '--fail', '--silent', url]
674- for (k,v) in headers.iteritems():
675- cmd += ['-H', '%s: %s' % (k,v)]
676-
677- cmd += ['-o', path]
678- return process.SharedPool().execute(executable=cmd[0], args=cmd[1:])
679+ if sys.platform.startswith('win'):
680+ return _fetch_image_no_curl(url, path, headers)
681+ else:
682+ cmd = ['/usr/bin/curl', '--fail', '--silent', url]
683+ for (k,v) in headers.iteritems():
684+ cmd += ['-H', '%s: %s' % (k,v)]
685+ cmd += ['-o', path]
686+ return process.SharedPool().execute(executable=cmd[0], args=cmd[1:])
687
688
689 def _fetch_local_image(image, path, user, project):
690- source = _image_path('%s/image' % image)
691- return process.simple_execute('cp %s %s' % (source, path))
692+ source = _image_path(os.path.join(image, 'image'))
693+ logging.debug("About to copy %s to %s", source, path)
694+ if sys.platform.startswith('win'):
695+ return shutil.copy(source, path)
696+ else:
697+ return process.simple_execute('cp %s %s' % (source, path))
698
699
700 def _image_path(path):