A plugin for Hyper-V control is available for CloudStack. The plugin implements basic VM control; however, its

architecture allows additional functionality to be easily added.  Incorporating the plugin in CloudStack will allow
the community to participate in improving the features available with Hyper-V. The plugin uses a Director Connect
Agent architecture described here: https://cwiki.apache.org/confluence/display/CLOUDSTACK/Progress
Add ability to pass kvp data via the key cloudstack-vm-userdata
Rearrange code to make it clearer what .NET objects are being used.
Test failures are easier to deal with if test key is not deleted.
Acquire management/pod ip for control ip when VR deploys in HyperV
Fixed deletion on VM's on hyperv host when mgmt server gets restarted due to HA
Implementation for attach iso command. Attaches an iso to a given vm.
This commit is contained in:
Donal Lafferty 2013-10-02 14:15:42 +05:30 committed by Devdeep Singh
parent f25354dca1
commit f9f196a46a
78 changed files with 56787 additions and 3 deletions

View File

@ -156,6 +156,17 @@
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.cloudstack</groupId>
<artifactId>cloud-plugin-hypervisor-hyperv</artifactId>
<version>${project.version}</version>
<exclusions>
<exclusion>
<groupId>org.mortbay.jetty</groupId>
<artifactId>servlet-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.cloudstack</groupId>
<artifactId>cloud-plugin-storage-allocator-random</artifactId>

View File

@ -0,0 +1,8 @@
packages
*.suo
*/obj/*
WmiWrappers/bin/*
AgentShell/bin/*
ServerResource*/bin/*
*.user

View File

@ -0,0 +1,53 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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.
namespace CloudStack.Plugin.AgentShell
{
partial class AgentService
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
this.ServiceName = "CloudStack ServerResource";
}
#endregion
}
}

View File

@ -0,0 +1,131 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http.SelfHost;
using System.Web.Http;
using log4net;
using HypervResource;
namespace CloudStack.Plugin.AgentShell
{
public partial class AgentService : ServiceBase
{
[System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError = true)]
static extern bool AllocConsole();
[System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError = true)]
static extern bool FreeConsole();
HttpSelfHostServer server;
private static ILog logger = LogManager.GetLogger(typeof(AgentService));
public AgentService()
{
logger.Info("Starting CloudStack agent");
InitializeComponent();
UriBuilder baseUri = new UriBuilder("http", AgentSettings.Default.private_ip_address, AgentSettings.Default.port);
var config = new HttpSelfHostConfiguration(baseUri.Uri);
// Allow ActionName to be applied to methods in ApiController, which allows it to serve multiple POST URLs
config.Routes.MapHttpRoute(
"API Default", "api/{controller}/{action}",
new { action = RouteParameter.Optional }
);
// Load controller assemblies that we want to config to route to.
ConfigServerResource();
AssertControllerAssemblyAvailable(config, typeof(HypervResourceController), "Cannot load Controller of type" + typeof(HypervResourceController));
server = new HttpSelfHostServer(config);
}
public static void ConfigServerResource()
{
// For simplicity, ServerResource config and settings file are tightly coupled.
// An alternative is to pass a dictionary to the server resource and let it find
// required settings. In contrast, the approach below is strongly typed and makes
// use of VisualStudio settings designer. The designer allows us to avoid
// accessing config using their key strings.
HypervResourceControllerConfig rsrcCnf = new HypervResourceControllerConfig();
rsrcCnf.PrivateIpAddress = AgentSettings.Default.private_ip_address;
rsrcCnf.GatewayIpAddress = AgentSettings.Default.gateway_ip_address;
rsrcCnf.RootDeviceReservedSpaceBytes = AgentSettings.Default.RootDeviceReservedSpaceBytes;
rsrcCnf.RootDeviceName = AgentSettings.Default.RootDeviceName;
rsrcCnf.ParentPartitionMinMemoryMb = AgentSettings.Default.dom0MinMemory;
rsrcCnf.LocalSecondaryStoragePath = AgentSettings.Default.local_secondary_storage_path;
// Side effect: loads the assembly containing HypervResourceController, which
// allows HttpSelfHostServer to route requests to the controller.
HypervResourceController.Configure(rsrcCnf);
}
// TODO: update to examine not the assembly resolver, but the list of available controllers themselves!
private static bool AssertControllerAssemblyAvailable(HttpSelfHostConfiguration config, Type controllerType, string errorMessage)
{
var assemblies = config.Services.GetAssembliesResolver().GetAssemblies();
foreach (var assembly in assemblies)
{
string name = assembly.GetName().Name;
if (controllerType.Assembly.GetName().Name.Equals(name))
{
logger.DebugFormat("Controller {0} is available", controllerType.Name);
return true;
}
}
logger.Error(errorMessage);
throw new AgentShellException(errorMessage);
}
protected override void OnStart(string[] args)
{
server.OpenAsync().Wait();
}
protected override void OnStop()
{
server.CloseAsync().Wait();
}
internal void RunConsole(string[] args)
{
OnStart(args);
AllocConsole();
Console.WriteLine("Service running ... press <ENTER> to stop");
Console.ReadLine();
FreeConsole();
OnStop();
}
}
}

View File

@ -0,0 +1,383 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.17929
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace CloudStack.Plugin.AgentShell {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
public sealed partial class AgentSettings : global::System.Configuration.ApplicationSettingsBase {
private static AgentSettings defaultInstance = ((AgentSettings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new AgentSettings())));
public static AgentSettings Default {
get {
return defaultInstance;
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("8")]
public int cpus {
get {
return ((int)(this["cpus"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("Routing")]
public string type {
get {
return ((string)(this["type"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("5fe2bad3-d785-394e-9949-89786b8a63d2")]
public global::System.Guid local_storage_uuid {
get {
return ((global::System.Guid)(this["local_storage_uuid"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("hvm")]
public string capabilities {
get {
return ((string)(this["capabilities"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("2130")]
public int Settingcpuspeed {
get {
return ((int)(this["Settingcpuspeed"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("8250")]
public int port {
get {
return ((int)(this["port"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("34359738368")]
public long memory {
get {
return ((long)(this["memory"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("camldonall01.citrite.net")]
public string host {
get {
return ((string)(this["host"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("1")]
public int pod {
get {
return ((int)(this["pod"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("10.1.1.1")]
public string gateway_ip_address {
get {
return ((string)(this["gateway_ip_address"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public global::System.Guid guid {
get {
return ((global::System.Guid)(this["guid"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("2")]
public int cluster {
get {
return ((int)(this["cluster"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("1")]
public int zone {
get {
return ((int)(this["zone"]));
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("c:\\Secondary")]
public string local_secondary_storage_path {
get {
return ((string)(this["local_secondary_storage_path"]));
}
set {
this["local_secondary_storage_path"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("E:\\Disks\\Disks")]
public string local_storage_path {
get {
return ((string)(this["local_storage_path"]));
}
set {
this["local_storage_path"] = value;
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("5")]
public int workers {
get {
return ((int)(this["workers"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("255.255.240.0")]
public string private_ip_netmask {
get {
return ((string)(this["private_ip_netmask"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("4294967296")]
public long RootDeviceReservedSpaceBytes {
get {
return ((long)(this["RootDeviceReservedSpaceBytes"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("..\\..\\..\\..\\..\\")]
public string hyperv_plugin_root {
get {
return ((string)(this["hyperv_plugin_root"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("e:\\")]
public string RootDeviceName {
get {
return ((string)(this["RootDeviceName"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("101F742C6B88")]
public string private_mac_address {
get {
return ((string)(this["private_mac_address"]));
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute(".\\var\\test\\storagepool")]
public string testLocalStorePath {
get {
return ((string)(this["testLocalStorePath"]));
}
set {
this["testLocalStorePath"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("testS3Bucket")]
public string testS3Bucket {
get {
return ((string)(this["testS3Bucket"]));
}
set {
this["testS3Bucket"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("testS3Endpoint")]
public string testS3Endpoint {
get {
return ((string)(this["testS3Endpoint"]));
}
set {
this["testS3Endpoint"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("testS3AccessKey")]
public string testS3AccessKey {
get {
return ((string)(this["testS3AccessKey"]));
}
set {
this["testS3AccessKey"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("testS3SecretKey")]
public string testS3SecretKey {
get {
return ((string)(this["testS3SecretKey"]));
}
set {
this["testS3SecretKey"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("206-2-73592258-559a-3b38-8f66-b667aab143eb")]
public string testS3TemplateName {
get {
return ((string)(this["testS3TemplateName"]));
}
set {
this["testS3TemplateName"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("5fe2bad3-d785-394e-9949-89786b8a63d2")]
public string testLocalStoreUUID {
get {
return ((string)(this["testLocalStoreUUID"]));
}
set {
this["testLocalStoreUUID"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("acton-systemvm-02062012.vhd.bz2")]
public string testSystemVMTemplateName {
get {
return ((string)(this["testSystemVMTemplateName"]));
}
set {
this["testSystemVMTemplateName"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("acton-systemvm-02062012")]
public string testSystemVMTemplateNameNoExt {
get {
return ((string)(this["testSystemVMTemplateNameNoExt"]));
}
set {
this["testSystemVMTemplateNameNoExt"] = value;
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("2048")]
public ulong dom0MinMemory {
get {
return ((ulong)(this["dom0MinMemory"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("10.1.1.1")]
public string private_ip_address {
get {
return ((string)(this["private_ip_address"]));
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("cifs://10.1.1.1/secondary?user\\u003dadministrator\\u0026password\\u003d1pass%40w" +
"ord1")]
public string testCifsUrl {
get {
return ((string)(this["testCifsUrl"]));
}
set {
this["testCifsUrl"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("template/tmpl/2/201/61d5316a-3cc4-30cf-a557-78691ff5c143.vhd")]
public string testCifsPath {
get {
return ((string)(this["testCifsPath"]));
}
set {
this["testCifsPath"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("CentOS64")]
public string testKvpVmName {
get {
return ((string)(this["testKvpVmName"]));
}
set {
this["testKvpVmName"] = value;
}
}
}
}

View File

@ -0,0 +1,111 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)" GeneratedClassNamespace="CloudStack.Plugin.AgentShell" GeneratedClassName="AgentSettings">
<Profiles />
<Settings>
<Setting Name="cpus" Type="System.Int32" Scope="Application">
<Value Profile="(Default)">8</Value>
</Setting>
<Setting Name="private_ip_address" Type="System.String" Scope="Application">
<Value Profile="(Default)">10.70.176.29</Value>
</Setting>
<Setting Name="type" Type="System.String" Scope="Application">
<Value Profile="(Default)">Routing</Value>
</Setting>
<Setting Name="local_storage_uuid" Type="System.Guid" Scope="Application">
<Value Profile="(Default)">5fe2bad3-d785-394e-9949-89786b8a63d2</Value>
</Setting>
<Setting Name="capabilities" Type="System.String" Scope="Application">
<Value Profile="(Default)">hvm</Value>
</Setting>
<Setting Name="Settingcpuspeed" Type="System.Int32" Scope="Application">
<Value Profile="(Default)">2130</Value>
</Setting>
<Setting Name="port" Type="System.Int32" Scope="Application">
<Value Profile="(Default)">8250</Value>
</Setting>
<Setting Name="memory" Type="System.Int64" Scope="Application">
<Value Profile="(Default)">34359738368</Value>
</Setting>
<Setting Name="host" Type="System.String" Scope="Application">
<Value Profile="(Default)">camldonall01.citrite.net</Value>
</Setting>
<Setting Name="pod" Type="System.Int32" Scope="Application">
<Value Profile="(Default)">1</Value>
</Setting>
<Setting Name="gateway_ip_address" Type="System.String" Scope="Application">
<Value Profile="(Default)">10.70.176.1</Value>
</Setting>
<Setting Name="guid" Type="System.Guid" Scope="Application">
<Value Profile="(Default)" />
</Setting>
<Setting Name="cluster" Type="System.Int32" Scope="Application">
<Value Profile="(Default)">2</Value>
</Setting>
<Setting Name="zone" Type="System.Int32" Scope="Application">
<Value Profile="(Default)">1</Value>
</Setting>
<Setting Name="local_secondary_storage_path" Type="System.String" Scope="User">
<Value Profile="(Default)">c:\Secondary</Value>
</Setting>
<Setting Name="local_storage_path" Type="System.String" Scope="User">
<Value Profile="(Default)">E:\Disks\Disks</Value>
</Setting>
<Setting Name="workers" Type="System.Int32" Scope="Application">
<Value Profile="(Default)">5</Value>
</Setting>
<Setting Name="private_ip_netmask" Type="System.String" Scope="Application">
<Value Profile="(Default)">255.255.240.0</Value>
</Setting>
<Setting Name="RootDeviceReservedSpaceBytes" Type="System.Int64" Scope="Application">
<Value Profile="(Default)">4294967296</Value>
</Setting>
<Setting Name="hyperv_plugin_root" Type="System.String" Scope="Application">
<Value Profile="(Default)">..\..\..\..\..\</Value>
</Setting>
<Setting Name="RootDeviceName" Type="System.String" Scope="Application">
<Value Profile="(Default)">e:\</Value>
</Setting>
<Setting Name="private_mac_address" Type="System.String" Scope="Application">
<Value Profile="(Default)">101F742C6B88</Value>
</Setting>
<Setting Name="testLocalStorePath" Type="System.String" Scope="User">
<Value Profile="(Default)">.\var\test\storagepool</Value>
</Setting>
<Setting Name="testS3Bucket" Type="System.String" Scope="User">
<Value Profile="(Default)">testS3Bucket</Value>
</Setting>
<Setting Name="testS3Endpoint" Type="System.String" Scope="User">
<Value Profile="(Default)">testS3Endpoint</Value>
</Setting>
<Setting Name="testS3AccessKey" Type="System.String" Scope="User">
<Value Profile="(Default)">testS3AccessKey</Value>
</Setting>
<Setting Name="testS3SecretKey" Type="System.String" Scope="User">
<Value Profile="(Default)">testS3SecretKey</Value>
</Setting>
<Setting Name="testS3TemplateName" Type="System.String" Scope="User">
<Value Profile="(Default)">206-2-73592258-559a-3b38-8f66-b667aab143eb</Value>
</Setting>
<Setting Name="testLocalStoreUUID" Type="System.String" Scope="User">
<Value Profile="(Default)">5fe2bad3-d785-394e-9949-89786b8a63d2</Value>
</Setting>
<Setting Name="testSystemVMTemplateName" Type="System.String" Scope="User">
<Value Profile="(Default)">acton-systemvm-02062012.vhd.bz2</Value>
</Setting>
<Setting Name="testSystemVMTemplateNameNoExt" Type="System.String" Scope="User">
<Value Profile="(Default)">acton-systemvm-02062012</Value>
</Setting>
<Setting Name="dom0MinMemory" Type="System.UInt64" Scope="Application">
<Value Profile="(Default)">2048</Value>
</Setting>
<Setting Name="testCifsUrl" Type="System.String" Scope="User">
<Value Profile="(Default)">cifs://10.1.1.1/secondary?user\u003dadministrator\u0026password\u003d1pass%40word1</Value>
</Setting>
<Setting Name="testCifsPath" Type="System.String" Scope="User">
<Value Profile="(Default)">template/tmpl/2/201/61d5316a-3cc4-30cf-a557-78691ff5c143.vhd</Value>
</Setting>
<Setting Name="testKvpVmName" Type="System.String" Scope="User">
<Value Profile="(Default)">CentOS64</Value>
</Setting>
</Settings>
</SettingsFile>

View File

@ -0,0 +1,135 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{9060B539-62D0-4E71-A6C6-5944828774E9}</ProjectGuid>
<OutputType>WinExe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>CloudStack.Plugin.AgentShell</RootNamespace>
<AssemblyName>AgentShell</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\</SolutionDir>
<RestorePackages>true</RestorePackages>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'NoUnitTestsDebug|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\NoUnitTestsDebug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'NoUnitTests|AnyCPU'">
<OutputPath>bin\NoUnitTests\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<ItemGroup>
<Reference Include="Ionic.Zip">
<HintPath>..\packages\DotNetZip.1.9.1.8\lib\net20\Ionic.Zip.dll</HintPath>
</Reference>
<Reference Include="log4net">
<HintPath>..\packages\log4net.2.0.0\lib\net40-full\log4net.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json">
<HintPath>..\packages\Newtonsoft.Json.4.5.11\lib\net40\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Management" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Net.Http.Formatting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNet.WebApi.Client.4.0.20710.0\lib\net40\System.Net.Http.Formatting.dll</HintPath>
</Reference>
<Reference Include="System.Net.Http.WebRequest" />
<Reference Include="System.Web.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNet.WebApi.Core.4.0.20710.0\lib\net40\System.Web.Http.dll</HintPath>
</Reference>
<Reference Include="System.Web.Http.SelfHost, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNet.WebApi.SelfHost.4.0.20918.0\lib\net40\System.Web.Http.SelfHost.dll</HintPath>
</Reference>
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.ServiceProcess" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="AgentService.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="AgentService.Designer.cs">
<DependentUpon>AgentService.cs</DependentUpon>
</Compile>
<Compile Include="AgentShellException.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="AgentSettings.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
<DependentUpon>AgentSettings.settings</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<None Include="App.config">
<SubType>Designer</SubType>
</None>
<None Include="packages.config">
<SubType>Designer</SubType>
</None>
<None Include="AgentSettings.settings">
<Generator>PublicSettingsSingleFileGenerator</Generator>
<LastGenOutput>AgentSettings.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\HypervResource\HypervResource.csproj">
<Project>{c963dfff-65ba-4e71-ada5-526a4da4e0b2}</Project>
<Name>HypervResource</Name>
</ProjectReference>
<ProjectReference Include="..\WmiWrappers\WmiWrappers.csproj">
<Project>{db824727-bdc3-437c-a364-7a811d8a160f}</Project>
<Name>WmiWrappers</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@ -0,0 +1,28 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CloudStack.Plugin.AgentShell
{
class AgentShellException : Exception
{
public AgentShellException(string errMsg) : base(errMsg) { }
}
}

View File

@ -0,0 +1,145 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="CloudStack.Plugin.AgentShell.AgentSettings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="CloudStack.Plugin.AgentShell.AgentSettings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<log4net>
<appender name="FileAppender" type="log4net.Appender.FileAppender">
<file value="cloudstack-agent.log" />
<appendToFile value="true" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<appender name="EventLogAppender" type="log4net.Appender.EventLogAppender">
<appendToFile value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline"/>
</layout>
</appender>
<root>
<level value="ALL"/>
<appender-ref ref="FileAppender"/>
</root>
</log4net>
<applicationSettings>
<CloudStack.Plugin.AgentShell.AgentSettings>
<setting name="cpus" serializeAs="String">
<value>8</value>
</setting>
<setting name="type" serializeAs="String">
<value>Routing</value>
</setting>
<setting name="local_storage_uuid" serializeAs="String">
<value>5fe2bad3-d785-394e-9949-89786b8a63d2</value>
</setting>
<setting name="capabilities" serializeAs="String">
<value>hvm</value>
</setting>
<setting name="Settingcpuspeed" serializeAs="String">
<value>2130</value>
</setting>
<setting name="port" serializeAs="String">
<value>8250</value>
</setting>
<setting name="memory" serializeAs="String">
<value>34359738368</value>
</setting>
<setting name="host" serializeAs="String">
<value>camldonall01.citrite.net</value>
</setting>
<setting name="pod" serializeAs="String">
<value>1</value>
</setting>
<setting name="gateway_ip_address" serializeAs="String">
<value>10.70.176.1</value>
</setting>
<setting name="cluster" serializeAs="String">
<value>2</value>
</setting>
<setting name="zone" serializeAs="String">
<value>1</value>
</setting>
<setting name="workers" serializeAs="String">
<value>5</value>
</setting>
<setting name="private_ip_netmask" serializeAs="String">
<value>255.255.240.0</value>
</setting>
<setting name="RootDeviceReservedSpaceBytes" serializeAs="String">
<value>4294967296</value>
</setting>
<setting name="hyperv_plugin_root" serializeAs="String">
<value>..\..\..\..\..\</value>
</setting>
<setting name="RootDeviceName" serializeAs="String">
<value>e:\</value>
</setting>
<setting name="private_mac_address" serializeAs="String">
<value>101F742C6B88</value>
</setting>
<setting name="dom0MinMemory" serializeAs="String">
<value>2048</value>
</setting>
<setting name="private_ip_address" serializeAs="String">
<value>10.70.1.1</value>
</setting>
</CloudStack.Plugin.AgentShell.AgentSettings>
</applicationSettings>
<userSettings>
<CloudStack.Plugin.AgentShell.AgentSettings>
<setting name="local_secondary_storage_path" serializeAs="String">
<value>c:\Secondary</value>
</setting>
<setting name="local_storage_path" serializeAs="String">
<value>E:\Disks\Disks</value>
</setting>
<setting name="testLocalStorePath" serializeAs="String">
<value>.\var\test\storagepool</value>
</setting>
<setting name="testS3Bucket" serializeAs="String">
<value>testS3Bucket</value>
</setting>
<setting name="testS3Endpoint" serializeAs="String">
<value>testS3Endpoint</value>
</setting>
<setting name="testS3AccessKey" serializeAs="String">
<value>testS3AccessKey</value>
</setting>
<setting name="testS3SecretKey" serializeAs="String">
<value>testS3SecretKey</value>
</setting>
<setting name="testS3TemplateName" serializeAs="String">
<value>206-2-73592258-559a-3b38-8f66-b667aab143eb</value>
</setting>
<setting name="testLocalStoreUUID" serializeAs="String">
<value>5fe2bad3-d785-394e-9949-89786b8a63d2</value>
</setting>
<setting name="testSystemVMTemplateName" serializeAs="String">
<value>acton-systemvm-02062012.vhd.bz2</value>
</setting>
<setting name="testSystemVMTemplateNameNoExt" serializeAs="String">
<value>acton-systemvm-02062012</value>
</setting>
<setting name="testCifsUrl" serializeAs="String">
<value>cifs://10.70.1.1/secondary?user\u003dadministrator\u0026password\u003d1pass%40word1</value>
</setting>
<setting name="testCifsPath" serializeAs="String">
<value>template/tmpl/2/201/61d5316a-3cc4-30cf-a557-78691ff5c143.vhd</value>
</setting>
</CloudStack.Plugin.AgentShell.AgentSettings>
</userSettings>
</configuration>

View File

@ -0,0 +1,58 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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.
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace CloudStack.Plugin.AgentShell
{
static class Program
{
private static ILog logger = LogManager.GetLogger(typeof(Program));
/// <summary>
/// Application entry point allows service to run in console application or as a Windows service.
/// Add '--console' to the commandline for the former, the latter is the default.
/// </summary>
static void Main(params string[] args)
{
string arg1 = string.Empty;
if (args.Length > 0)
{
arg1 = args[0];
logger.DebugFormat("CloudStack ServerResource arg is ", arg1);
}
if (string.Compare(arg1, "--console", true) == 0)
{
logger.InfoFormat("CloudStack ServerResource running as console app");
new AgentService().RunConsole(args);
}
else
{
logger.InfoFormat("CloudStack ServerResource running as Windows Service");
ServiceBase[] ServicesToRun = new ServiceBase[] { new AgentService() };
ServiceBase.Run(ServicesToRun);
}
}
}
}

View File

@ -0,0 +1,39 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AgentShell")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AgentShell")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a6d8469a-c815-4765-a4a1-4927d4e3c583")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: log4net.Config.XmlConfigurator(Watch = true)]

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="DotNetZip" version="1.9.1.8" targetFramework="net45" />
<package id="log4net" version="2.0.0" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.Client" version="4.0.20710.0" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.Core" version="4.0.20710.0" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.SelfHost" version="4.0.20918.0" targetFramework="net45" />
<package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net45" />
<package id="Newtonsoft.Json" version="4.5.11" targetFramework="net45" />
</packages>

View File

@ -0,0 +1,128 @@
<?xml version="1.0" encoding="utf-8" ?>
<!--
Note: Add entries to the App.config file for configuration settings
that apply only to the Test project.
-->
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="CloudStack.Plugin.AgentShell.AgentSettings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="CloudStack.Plugin.AgentShell.AgentSettings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<appSettings>
</appSettings>
<connectionStrings>
</connectionStrings>
<applicationSettings>
<CloudStack.Plugin.AgentShell.AgentSettings>
<setting name="cpus" serializeAs="String">
<value>8</value>
</setting>
<setting name="private_ip_address" serializeAs="String">
<value>10.1.1.1</value>
</setting>
<setting name="type" serializeAs="String">
<value>Routing</value>
</setting>
<setting name="local_storage_uuid" serializeAs="String">
<value>5fe2bad3-d785-394e-9949-89786b8a63d2</value>
</setting>
<setting name="capabilities" serializeAs="String">
<value>hvm</value>
</setting>
<setting name="Settingcpuspeed" serializeAs="String">
<value>2130</value>
</setting>
<setting name="port" serializeAs="String">
<value>8250</value>
</setting>
<setting name="memory" serializeAs="String">
<value>34359738368</value>
</setting>
<setting name="host" serializeAs="String">
<value>camldonall01.citrite.net</value>
</setting>
<setting name="pod" serializeAs="String">
<value>1</value>
</setting>
<setting name="gateway_ip_address" serializeAs="String">
<value>10.70.176.1</value>
</setting>
<setting name="cluster" serializeAs="String">
<value>2</value>
</setting>
<setting name="zone" serializeAs="String">
<value>1</value>
</setting>
<setting name="local_storage_path" serializeAs="String">
<value>E:\Disks\Disks</value>
</setting>
<setting name="workers" serializeAs="String">
<value>5</value>
</setting>
<setting name="private_ip_netmask" serializeAs="String">
<value>255.255.240.0</value>
</setting>
<setting name="RootDeviceReservedSpaceBytes" serializeAs="String">
<value>4294967296</value>
</setting>
<setting name="hyperv_plugin_root" serializeAs="String">
<value>..\..\..\..\..\</value>
</setting>
<setting name="RootDeviceName" serializeAs="String">
<value>e:\</value>
</setting>
<setting name="dom0MinMemory" serializeAs="String">
<value>2048</value>
</setting>
<setting name="private_mac_address" serializeAs="String">
<value>101F742C6B88</value>
</setting>
</CloudStack.Plugin.AgentShell.AgentSettings>
</applicationSettings>
<userSettings>
<CloudStack.Plugin.AgentShell.AgentSettings>
<setting name="local_secondary_storage_path" serializeAs="String">
<value>c:\Secondary</value>
</setting>
<setting name="local_storage_path" serializeAs="String">
<value>E:\Disks\Disks</value>
</setting>
<setting name="testLocalStoreUUID" serializeAs="String">
<value>5fe2bad3-d785-394e-9949-89786b8a63d2</value>
</setting>
<setting name="testLocalStorePath" serializeAs="String">
<value>.\var\test\storagepool</value>
</setting>
<setting name="testS3Bucket" serializeAs="String">
<value>cshv3eu</value>
</setting>
<setting name="testS3Endpoint" serializeAs="String">
<value>s3.amazonaws.com</value>
</setting>
<setting name="testS3AccessKey" serializeAs="String">
<value>testS3AccessKey</value>
</setting>
<setting name="testS3SecretKey" serializeAs="String">
<value>testS3SecretKey</value>
</setting>
<setting name="testS3TemplateName" serializeAs="String">
<value>206-2-73592258-559a-3b38-8f66-b667aab143eb</value>
</setting>
<setting name="testCifsTemplateName" serializeAs="String">
<value>206-2-73592258-559a-3b38-8f66-b667aab143eb</value>
</setting>
<setting name="testCifsUrl" serializeAs="String">
<value>cifs://10.1.1.1/secondary?user\u003dadministrator\u0026password\u003d1pass%40word1</value>
</setting>
<setting name="testCifsPath" serializeAs="String">
<value>template/tmpl/2/201/6dda6631-4daa-3150-a49a-d5a4b0a4c4b6.vhd</value>
</setting>
</CloudStack.Plugin.AgentShell.AgentSettings>
</userSettings>
</configuration>

View File

@ -0,0 +1,642 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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.
using log4net;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
// C# versions of certain CloudStack types to simplify JSON serialisation.
// Limit to the number of types, becasue they are written and maintained manually.
// JsonProperty used to identify property name when serialised, which allows
// later adoption of C# naming conventions if requried.
namespace HypervResource
{
public class PrimaryDataStoreTO
{
public string path;
public static PrimaryDataStoreTO ParseJson(dynamic json)
{
PrimaryDataStoreTO result = null;
if (json == null)
{
return result;
}
dynamic primaryDataStoreTOJson = json[CloudStackTypes.PrimaryDataStoreTO];
if (primaryDataStoreTOJson != null)
{
result = new PrimaryDataStoreTO()
{
path = (string)primaryDataStoreTOJson.path
};
}
return result;
}
}
public class VolumeObjectTO
{
private static ILog logger = LogManager.GetLogger(typeof(VolumeObjectTO));
public string FullFileName
{
get
{
String result = Path.Combine(this.primaryDataStore.path, this.name);
if (this.format != null)
{
result = result + "." + this.format.ToLowerInvariant();
}
return result;
}
}
public dynamic dataStore;
public string format;
public string name;
public string uuid;
public PrimaryDataStoreTO primaryDataStore;
public static VolumeObjectTO ParseJson(dynamic json)
{
VolumeObjectTO result = null;
if (json == null)
{
return result;
}
dynamic volumeObjectTOJson = json[CloudStackTypes.VolumeObjectTO];
if (volumeObjectTOJson != null)
{
result = new VolumeObjectTO()
{
dataStore = volumeObjectTOJson.dataStore,
format = ((string)volumeObjectTOJson.format),
name = (string)volumeObjectTOJson.name,
uuid = (string)volumeObjectTOJson.uuid
};
result.primaryDataStore = PrimaryDataStoreTO.ParseJson(volumeObjectTOJson.dataStore);
// Assert
if (result.dataStore == null || result.primaryDataStore == null)
{
String errMsg = "VolumeObjectTO missing primary dataStore in spec " + volumeObjectTOJson.ToString();
logger.Error(errMsg);
throw new ArgumentNullException(errMsg);
}
GuessFileExtension(result);
}
return result;
}
private static void GuessFileExtension(VolumeObjectTO volInfo)
{
if (String.IsNullOrEmpty(volInfo.format))
{
logger.Info("No image format in VolumeObjectTO, going to use format from first file that matches " + volInfo.FullFileName);
string[] choices = Directory.GetFiles(volInfo.primaryDataStore.path, volInfo.name + ".vhd*");
if (choices.Length != 1)
{
String errMsg = "Tried to guess file extension, but cannot find file corresponding to " + Path.Combine(volInfo.primaryDataStore.path, volInfo.name); // format being guessed.
logger.Debug(errMsg);
}
else
{
string[] splitFileName = choices[0].Split(new char[] { '.' });
volInfo.format = splitFileName[splitFileName.Length - 1];
}
logger.Debug("Going to use file " + volInfo.FullFileName);
}
}
}
public class TemplateObjectTO
{
/// <summary>
/// Full file name varies depending on whether the TemplateObjectTO has a path or not.
/// If it has a path, we use that. Otherwise, we build it from the name, extension and data store path.
/// </summary>
public string FullFileName
{
get
{
if (String.IsNullOrEmpty(this.path))
{
return Path.Combine(this.primaryDataStore.path, this.name) + '.' + this.format.ToLowerInvariant();
}
return this.path;
}
}
public dynamic imageDataStore;
public string format;
public string name;
public string uuid;
public S3TO s3DataStoreTO = null;
public NFSTO nfsDataStoreTO = null;
public PrimaryDataStoreTO primaryDataStore = null;
public string path;
public string checksum;
public static TemplateObjectTO ParseJson(dynamic json)
{
TemplateObjectTO result = null;
dynamic templateObjectTOJson = json[CloudStackTypes.TemplateObjectTO];
if (templateObjectTOJson != null)
{
result = new TemplateObjectTO()
{
imageDataStore = templateObjectTOJson.imageDataStore,
format = (string)templateObjectTOJson.format,
name = (string)templateObjectTOJson.name,
uuid = (string)templateObjectTOJson.uuid,
path = (string)templateObjectTOJson.path,
checksum = (string)templateObjectTOJson.checksum
};
result.s3DataStoreTO = S3TO.ParseJson(templateObjectTOJson.imageDataStore);
result.nfsDataStoreTO = NFSTO.ParseJson(templateObjectTOJson.imageDataStore);
result.primaryDataStore = PrimaryDataStoreTO.ParseJson(templateObjectTOJson.imageDataStore);
}
return result;
}
}
public class S3TO
{
public string bucketName;
public string secretKey;
public string accessKey;
public string endpoint;
public bool httpsFlag;
public static S3TO ParseJson(dynamic json)
{
S3TO result = null;
dynamic s3TOJson = json[CloudStackTypes.S3TO];
if (s3TOJson != null)
{
result = new S3TO()
{
bucketName = (string)s3TOJson.bucketName,
secretKey = (string)s3TOJson.secretKey,
accessKey = (string)s3TOJson.accessKey,
endpoint = (string)s3TOJson.endPoint,
httpsFlag = (bool)s3TOJson.httpsFlag
};
// Delete security credentials in original command. Prevents logger from spilling the beans, as it were.
s3TOJson.secretKey = string.Empty;
s3TOJson.accessKey = string.Empty;
}
return result;
}
}
public class NFSTO
{
public Uri uri;
public string _role;
public string UncPath
{
get
{
string uncPath = null;
if (uri.Scheme.Equals("cifs"))
{
uncPath = @"\\" + uri.Host + uri.LocalPath;
}
return uncPath;
}
}
public string User
{
get
{
var queryDictionary = System.Web.HttpUtility.ParseQueryString(uri.Query);
return System.Web.HttpUtility.UrlDecode(queryDictionary["user"]);
}
}
public string Password
{
get
{
var queryDictionary = System.Web.HttpUtility.ParseQueryString(uri.Query);
return System.Web.HttpUtility.UrlDecode(queryDictionary["password"]);
}
}
public string Domain
{
get
{
var queryDictionary = System.Web.HttpUtility.ParseQueryString(uri.Query);
if (queryDictionary["domain"] != null)
{
return System.Web.HttpUtility.UrlDecode(queryDictionary["domain"]);
}
else return uri.Host;
}
}
public static NFSTO ParseJson(dynamic json)
{
NFSTO result = null;
dynamic nfsTOJson = json[CloudStackTypes.NFSTO];
if (nfsTOJson != null)
{
result = new NFSTO()
{
_role = (string)nfsTOJson._role,
};
// Delete security credentials in original command. Prevents logger from spilling the beans, as it were.
String uriStr = (String)nfsTOJson._url;
result.uri = new Uri(uriStr);
}
return result;
}
}
enum VolumeType
{
UNKNOWN,
ROOT,
SWAP,
DATADISK,
ISO
};
public enum StoragePoolType
{
/// <summary>
/// local directory
/// </summary>
Filesystem,
/// <summary>
/// NFS or CIFS
/// </summary>
NetworkFilesystem,
/// <summary>
/// shared LUN, with a clusterfs overlay
/// </summary>
IscsiLUN,
/// <summary>
/// for e.g., ZFS Comstar
/// </summary>
Iscsi,
/// <summary>
/// for iso image
/// </summary>
ISO,
/// <summary>
/// XenServer local LVM SR
/// </summary>
LVM,
/// <summary>
///
/// </summary>
CLVM,
/// <summary>
///
/// </summary>
RBD,
/// <summary>
///
/// </summary>
SharedMountPoint,
/// <summary>
/// VMware VMFS storage
/// </summary>
VMFS,
/// <summary>
/// for XenServer, Storage Pool is set up by customers.
/// </summary>
PreSetup,
/// <summary>
/// XenServer local EXT SR
/// </summary>
EXT,
/// <summary>
///
/// </summary>
OCFS2
}
public enum StorageResourceType
{
STORAGE_POOL, STORAGE_HOST, SECONDARY_STORAGE, LOCAL_SECONDARY_STORAGE
}
public struct VolumeInfo
{
public long id;
public string type;
public string storagePoolType;
public string storagePoolUuid;
public string name;
public string mountPoint;
public string path;
long size;
string chainInfo;
public VolumeInfo(long id, string type, string poolType, String poolUuid, String name, String mountPoint, String path, long size, String chainInfo)
{
this.id = id;
this.name = name;
this.path = path;
this.size = size;
this.type = type;
this.storagePoolType = poolType;
this.storagePoolUuid = poolUuid;
this.mountPoint = mountPoint;
this.chainInfo = chainInfo;
}
}
public struct StoragePoolInfo
{
[JsonProperty("uuid")]
public String uuid;
[JsonProperty("host")]
String host;
[JsonProperty("localPath")]
String localPath;
[JsonProperty("hostPath")]
String hostPath;
[JsonProperty("poolType")]
string poolType;
[JsonProperty("capacityBytes")]
long capacityBytes;
// Management server copies this field to the 'used_byptes' in the database table 'storage_pool'.
[JsonProperty("availableBytes")]
long availableBytes;
[JsonProperty("details")]
Dictionary<String, String> details;
public StoragePoolInfo(String uuid, String host, String hostPath,
String localPath, string poolType, long capacityBytes,
long availableBytes)
{
this.uuid = uuid;
this.host = host;
this.localPath = localPath;
this.hostPath = hostPath;
this.poolType = poolType;
this.capacityBytes = capacityBytes;
this.availableBytes = availableBytes;
details = null;
}
public StoragePoolInfo(String uuid, String host, String hostPath,
String localPath, string poolType, long capacityBytes,
long availableBytes, Dictionary<String, String> details)
: this(uuid, host, hostPath, localPath, poolType, capacityBytes, availableBytes)
{
this.details = details;
}
}
public class VmStatsEntry
{
[JsonProperty("cpuUtilization")]
public double cpuUtilization;
[JsonProperty("networkReadKBs")]
public double networkReadKBs;
[JsonProperty("networkWriteKBs")]
public double networkWriteKBs;
[JsonProperty("numCPUs")]
public int numCPUs;
[JsonProperty("entityType")]
public String entityType;
}
/// <summary>
/// Fully qualified named for a number of types used in CloudStack. Used to specify the intended type for JSON serialised objects.
/// </summary>
public class CloudStackTypes
{
public const string Answer = "com.cloud.agent.api.Answer";
public const string AttachIsoCommand = "com.cloud.agent.api.AttachIsoCommand";
public const string AttachVolumeAnswer = "com.cloud.agent.api.AttachVolumeAnswer";
public const string AttachVolumeCommand = "com.cloud.agent.api.AttachVolumeCommand";
public const string AnsBackupSnapshotAnswerwer = "com.cloud.agent.api.BackupSnapshotAnswer";
public const string BackupSnapshotCommand = "com.cloud.agent.api.BackupSnapshotCommand";
public const string BumpUpPriorityCommand = "com.cloud.agent.api.BumpUpPriorityCommand";
public const string CheckHealthAnswer = "com.cloud.agent.api.CheckHealthAnswer";
public const string CheckHealthCommand = "com.cloud.agent.api.CheckHealthCommand";
public const string CheckNetworkAnswer = "com.cloud.agent.api.CheckNetworkAnswer";
public const string CheckNetworkCommand = "com.cloud.agent.api.CheckNetworkCommand";
public const string CheckOnHostAnswer = "com.cloud.agent.api.CheckOnHostAnswer";
public const string CheckOnHostCommand = "com.cloud.agent.api.CheckOnHostCommand";
public const string CheckRouterAnswer = "com.cloud.agent.api.CheckRouterAnswer";
public const string CheckRouterCommand = "com.cloud.agent.api.CheckRouterCommand";
public const string CheckS2SVpnConnectionsAnswer = "com.cloud.agent.api.CheckS2SVpnConnectionsAnswer";
public const string CheckS2SVpnConnectionsCommand = "com.cloud.agent.api.CheckS2SVpnConnectionsCommand";
public const string CheckVirtualMachineAnswer = "com.cloud.agent.api.CheckVirtualMachineAnswer";
public const string CheckVirtualMachineCommand = "com.cloud.agent.api.CheckVirtualMachineCommand";
public const string CleanupNetworkRulesCmd = "com.cloud.agent.api.CleanupNetworkRulesCmd";
public const string ClusterSyncAnswer = "com.cloud.agent.api.ClusterSyncAnswer";
public const string ClusterSyncCommand = "com.cloud.agent.api.ClusterSyncCommand";
public const string Command = "com.cloud.agent.api.Command";
public const string CreatePrivateTemplateFromSnapshotCommand = "com.cloud.agent.api.CreatePrivateTemplateFromSnapshotCommand";
public const string CreatePrivateTemplateFromVolumeCommand = "com.cloud.agent.api.CreatePrivateTemplateFromVolumeCommand";
public const string CreateStoragePoolCommand = "com.cloud.agent.api.CreateStoragePoolCommand";
public const string CreateVMSnapshotAnswer = "com.cloud.agent.api.CreateVMSnapshotAnswer";
public const string CreateVMSnapshotCommand = "com.cloud.agent.api.CreateVMSnapshotCommand";
public const string CreateVolumeFromSnapshotAnswer = "com.cloud.agent.api.CreateVolumeFromSnapshotAnswer";
public const string CreateVolumeFromSnapshotCommand = "com.cloud.agent.api.CreateVolumeFromSnapshotCommand";
public const string DeleteStoragePoolCommand = "com.cloud.agent.api.DeleteStoragePoolCommand";
public const string DeleteVMSnapshotAnswer = "com.cloud.agent.api.DeleteVMSnapshotAnswer";
public const string DeleteVMSnapshotCommand = "com.cloud.agent.api.DeleteVMSnapshotCommand";
public const string GetDomRVersionAnswer = "com.cloud.agent.api.GetDomRVersionAnswer";
public const string GetDomRVersionCmd = "com.cloud.agent.api.GetDomRVersionCmd";
public const string GetHostStatsAnswer = "com.cloud.agent.api.GetHostStatsAnswer";
public const string GetHostStatsCommand = "com.cloud.agent.api.GetHostStatsCommand";
public const string GetStorageStatsAnswer = "com.cloud.agent.api.GetStorageStatsAnswer";
public const string GetStorageStatsCommand = "com.cloud.agent.api.GetStorageStatsCommand";
public const string GetVmDiskStatsAnswer = "com.cloud.agent.api.GetVmDiskStatsAnswer";
public const string GetVmDiskStatsCommand = "com.cloud.agent.api.GetVmDiskStatsCommand";
public const string GetVmStatsAnswer = "com.cloud.agent.api.GetVmStatsAnswer";
public const string GetVmStatsCommand = "com.cloud.agent.api.GetVmStatsCommand";
public const string GetVncPortAnswer = "com.cloud.agent.api.GetVncPortAnswer";
public const string GetVncPortCommand = "com.cloud.agent.api.GetVncPortCommand";
public const string HostStatsEntry = "com.cloud.agent.api.HostStatsEntry";
public const string MaintainAnswer = "com.cloud.agent.api.MaintainAnswer";
public const string MaintainCommand = "com.cloud.agent.api.MaintainCommand";
public const string ManageSnapshotAnswer = "com.cloud.agent.api.ManageSnapshotAnswer";
public const string ManageSnapshotCommand = "com.cloud.agent.api.ManageSnapshotCommand";
public const string MigrateAnswer = "com.cloud.agent.api.MigrateAnswer";
public const string MigrateCommand = "com.cloud.agent.api.MigrateCommand";
public const string ModifySshKeysCommand = "com.cloud.agent.api.ModifySshKeysCommand";
public const string ModifyStoragePoolAnswer = "com.cloud.agent.api.ModifyStoragePoolAnswer";
public const string ModifyStoragePoolCommand = "com.cloud.agent.api.ModifyStoragePoolCommand";
public const string NetworkRulesSystemVmCommand = "com.cloud.agent.api.NetworkRulesSystemVmCommand";
public const string NetworkRulesVmSecondaryIpCommand = "com.cloud.agent.api.NetworkRulesVmSecondaryIpCommand";
public const string PingCommand = "com.cloud.agent.api.PingCommand";
public const string PingRoutingCommand = "com.cloud.agent.api.PingRoutingCommand";
public const string PingRoutingWithNwGroupsCommand = "com.cloud.agent.api.PingRoutingWithNwGroupsCommand";
public const string PingRoutingWithOvsCommand = "com.cloud.agent.api.PingRoutingWithOvsCommand";
public const string PingTestCommand = "com.cloud.agent.api.PingTestCommand";
public const string PlugNicAnswer = "com.cloud.agent.api.PlugNicAnswer";
public const string PlugNicCommand = "com.cloud.agent.api.PlugNicCommand";
public const string PoolEjectCommand = "com.cloud.agent.api.PoolEjectCommand";
public const string PrepareForMigrationAnswer = "com.cloud.agent.api.PrepareForMigrationAnswer";
public const string PrepareForMigrationCommand = "com.cloud.agent.api.PrepareForMigrationCommand";
public const string PvlanSetupCommand = "com.cloud.agent.api.PvlanSetupCommand";
public const string ReadyAnswer = "com.cloud.agent.api.ReadyAnswer";
public const string ReadyCommand = "com.cloud.agent.api.ReadyCommand";
public const string RebootAnswer = "com.cloud.agent.api.RebootAnswer";
public const string RebootCommand = "com.cloud.agent.api.RebootCommand";
public const string RebootRouterCommand = "com.cloud.agent.api.RebootRouterCommand";
public const string RevertToVMSnapshotAnswer = "com.cloud.agent.api.RevertToVMSnapshotAnswer";
public const string RevertToVMSnapshotCommand = "com.cloud.agent.api.RevertToVMSnapshotCommand";
public const string ScaleVmAnswer = "com.cloud.agent.api.ScaleVmAnswer";
public const string ScaleVmCommand = "com.cloud.agent.api.ScaleVmCommand";
public const string SecurityGroupRuleAnswer = "com.cloud.agent.api.SecurityGroupRuleAnswer";
public const string SecurityGroupRulesCmd = "com.cloud.agent.api.SecurityGroupRulesCmd";
public const string SetupAnswer = "com.cloud.agent.api.SetupAnswer";
public const string SetupCommand = "com.cloud.agent.api.SetupCommand";
public const string SetupGuestNetworkAnswer = "com.cloud.agent.api.SetupGuestNetworkAnswer";
public const string SetupGuestNetworkCommand = "com.cloud.agent.api.SetupGuestNetworkCommand";
public const string StartAnswer = "com.cloud.agent.api.StartAnswer";
public const string StartCommand = "com.cloud.agent.api.StartCommand";
public const string StartupCommand = "com.cloud.agent.api.StartupCommand";
public const string StartupRoutingCommand = "com.cloud.agent.api.StartupRoutingCommand";
public const string StartupStorageCommand = "com.cloud.agent.api.StartupStorageCommand";
public const string StopAnswer = "com.cloud.agent.api.StopAnswer";
public const string StopCommand = "com.cloud.agent.api.StopCommand";
public const string StoragePoolInfo = "com.cloud.agent.api.StoragePoolInfo";
public const string UnPlugNicAnswer = "com.cloud.agent.api.UnPlugNicAnswer";
public const string UnPlugNicCommand = "com.cloud.agent.api.UnPlugNicCommand";
public const string UpdateHostPasswordCommand = "com.cloud.agent.api.UpdateHostPasswordCommand";
public const string UpgradeSnapshotCommand = "com.cloud.agent.api.UpgradeSnapshotCommand";
public const string VmDiskStatsEntry = "com.cloud.agent.api.VmDiskStatsEntry";
public const string VmStatsEntry = "com.cloud.agent.api.VmStatsEntry";
public const string CheckSshAnswer = "com.cloud.agent.api.check.CheckSshAnswer";
public const string CheckSshCommand = "com.cloud.agent.api.check.CheckSshCommand";
public const string CheckConsoleProxyLoadCommand = "com.cloud.agent.api.proxy.CheckConsoleProxyLoadCommand";
public const string ConsoleProxyLoadAnswer = "com.cloud.agent.api.proxy.ConsoleProxyLoadAnswer";
public const string WatchConsoleProxyLoadCommand = "com.cloud.agent.api.proxy.WatchConsoleProxyLoadCommand";
public const string CreateIpAliasCommand = "com.cloud.agent.api.routing.CreateIpAliasCommand";
public const string DeleteIpAliasCommand = "com.cloud.agent.api.routing.DeleteIpAliasCommand";
public const string DhcpEntryCommand = "com.cloud.agent.api.routing.DhcpEntryCommand";
public const string DnsMasqConfigCommand = "com.cloud.agent.api.routing.DnsMasqConfigCommand";
public const string IpAliasTO = "com.cloud.agent.api.routing.IpAliasTO";
public const string IpAssocAnswer = "com.cloud.agent.api.routing.IpAssocAnswer";
public const string IpAssocCommand = "com.cloud.agent.api.routing.IpAssocCommand";
public const string IpAssocVpcCommand = "com.cloud.agent.api.routing.IpAssocVpcCommand";
public const string LoadBalancerConfigCommand = "com.cloud.agent.api.routing.LoadBalancerConfigCommand";
public const string NetworkElementCommand = "com.cloud.agent.api.routing.NetworkElementCommand";
public const string RemoteAccessVpnCfgCommand = "com.cloud.agent.api.routing.RemoteAccessVpnCfgCommand";
public const string SavePasswordCommand = "com.cloud.agent.api.routing.SavePasswordCommand";
public const string SetFirewallRulesAnswer = "com.cloud.agent.api.routing.SetFirewallRulesAnswer";
public const string SetFirewallRulesCommand = "com.cloud.agent.api.routing.SetFirewallRulesCommand";
public const string SetNetworkACLAnswer = "com.cloud.agent.api.routing.SetNetworkACLAnswer";
public const string SetNetworkACLCommand = "com.cloud.agent.api.routing.SetNetworkACLCommand";
public const string SetPortForwardingRulesAnswer = "com.cloud.agent.api.routing.SetPortForwardingRulesAnswer";
public const string SetPortForwardingRulesCommand = "com.cloud.agent.api.routing.SetPortForwardingRulesCommand";
public const string SetPortForwardingRulesVpcCommand = "com.cloud.agent.api.routing.SetPortForwardingRulesVpcCommand";
public const string SetSourceNatAnswer = "com.cloud.agent.api.routing.SetSourceNatAnswer";
public const string SetSourceNatCommand = "com.cloud.agent.api.routing.SetSourceNatCommand";
public const string SetStaticNatRulesAnswer = "com.cloud.agent.api.routing.SetStaticNatRulesAnswer";
public const string SetStaticNatRulesCommand = "com.cloud.agent.api.routing.SetStaticNatRulesCommand";
public const string SetStaticRouteAnswer = "com.cloud.agent.api.routing.SetStaticRouteAnswer";
public const string SetStaticRouteCommand = "com.cloud.agent.api.routing.SetStaticRouteCommand";
public const string Site2SiteVpnCfgCommand = "com.cloud.agent.api.routing.Site2SiteVpnCfgCommand";
public const string VmDataCommand = "com.cloud.agent.api.routing.VmDataCommand";
public const string VpnUsersCfgCommand = "com.cloud.agent.api.routing.VpnUsersCfgCommand";
public const string CopyVolumeAnswer = "com.cloud.agent.api.storage.CopyVolumeAnswer";
public const string CopyVolumeCommand = "com.cloud.agent.api.storage.CopyVolumeCommand";
public const string CreateAnswer = "com.cloud.agent.api.storage.CreateAnswer";
public const string CreateCommand = "com.cloud.agent.api.storage.CreateCommand";
public const string CreatePrivateTemplateAnswer = "com.cloud.agent.api.storage.CreatePrivateTemplateAnswer";
public const string DestroyCommand = "com.cloud.agent.api.storage.DestroyCommand";
public const string PrimaryStorageDownloadAnswer = "com.cloud.agent.api.storage.PrimaryStorageDownloadAnswer";
public const string PrimaryStorageDownloadCommand = "com.cloud.agent.api.storage.PrimaryStorageDownloadCommand";
public const string ResizeVolumeAnswer = "com.cloud.agent.api.storage.ResizeVolumeAnswer";
public const string ResizeVolumeCommand = "com.cloud.agent.api.storage.ResizeVolumeCommand";
public const string FirewallRuleTO = "com.cloud.agent.api.to.FirewallRuleTO";
public const string IpAddressTO = "com.cloud.agent.api.to.IpAddressTO";
public const string NicTO = "com.cloud.agent.api.to.NicTO";
public const string PortForwardingRuleTO = "com.cloud.agent.api.to.PortForwardingRuleTO";
public const string S3TO = "com.cloud.agent.api.to.S3TO";
public const string NFSTO = "com.cloud.agent.api.to.NfsTO";
public const string StaticNatRuleTO = "com.cloud.agent.api.to.StaticNatRuleTO";
public const string StorageFilerTO = "com.cloud.agent.api.to.StorageFilerTO";
public const string SwiftTO = "com.cloud.agent.api.to.SwiftTO";
public const string VirtualMachineTO = "com.cloud.agent.api.to.VirtualMachineTO";
public const string VolumeTO = "com.cloud.agent.api.to.VolumeTO";
public const string InternalErrorException = "com.cloud.exception.InternalErrorException";
public const string HostType = "com.cloud.host.Host.Type";
public const string HypervisorType = "com.cloud.hypervisor.Hypervisor.HypervisorType";
public const string DnsMasqConfigurator = "com.cloud.network.DnsMasqConfigurator";
public const string HAProxyConfigurator = "com.cloud.network.HAProxyConfigurator";
public const string LoadBalancerConfigurator = "com.cloud.network.LoadBalancerConfigurator";
public const string Networks = "com.cloud.network.Networks";
public const string BroadcastDomainType = "com.cloud.network.Networks.BroadcastDomainType";
public const string IsolationType = "com.cloud.network.Networks.IsolationType";
public const string TrafficType = "com.cloud.network.Networks.TrafficType";
public const string PhysicalNetworkSetupInfo = "com.cloud.network.PhysicalNetworkSetupInfo";
public const string OvsCreateGreTunnelAnswer = "com.cloud.network.ovs.OvsCreateGreTunnelAnswer";
public const string OvsCreateGreTunnelCommand = "com.cloud.network.ovs.OvsCreateGreTunnelCommand";
public const string OvsCreateTunnelAnswer = "com.cloud.network.ovs.OvsCreateTunnelAnswer";
public const string OvsCreateTunnelCommand = "com.cloud.network.ovs.OvsCreateTunnelCommand";
public const string OvsDeleteFlowCommand = "com.cloud.network.ovs.OvsDeleteFlowCommand";
public const string OvsDestroyBridgeCommand = "com.cloud.network.ovs.OvsDestroyBridgeCommand";
public const string OvsDestroyTunnelCommand = "com.cloud.network.ovs.OvsDestroyTunnelCommand";
public const string OvsFetchInterfaceAnswer = "com.cloud.network.ovs.OvsFetchInterfaceAnswer";
public const string OvsFetchInterfaceCommand = "com.cloud.network.ovs.OvsFetchInterfaceCommand";
public const string OvsSetTagAndFlowAnswer = "com.cloud.network.ovs.OvsSetTagAndFlowAnswer";
public const string OvsSetTagAndFlowCommand = "com.cloud.network.ovs.OvsSetTagAndFlowCommand";
public const string OvsSetupBridgeCommand = "com.cloud.network.ovs.OvsSetupBridgeCommand";
public const string FirewallRule = "com.cloud.network.rules.FirewallRule";
public const string ServerResource = "com.cloud.resource.ServerResource";
public const string HypervisorResource = "com.cloud.resource.hypervisor.HypervisorResource";
public const string Storage = "com.cloud.storage.Storage";
public const string ImageFormat = "com.cloud.storage.Storage.ImageFormat";
public const string StoragePoolType = "com.cloud.storage.Storage.StoragePoolType";
public const string Volume = "com.cloud.storage.Volume";
public const string VolumeVO = "com.cloud.storage.VolumeVO";
public const string StorageSubsystemCommandHandler = "com.cloud.storage.resource.StorageSubsystemCommandHandler";
public const string StorageSubsystemCommandHandlerBase = "com.cloud.storage.resource.StorageSubsystemCommandHandlerBase";
public const string TemplateProp = "com.cloud.storage.template.TemplateProp";
public const string BootloaderType = "com.cloud.template.VirtualMachineTemplate.BootloaderType";
public const string VolumeObjectTO = "org.apache.cloudstack.storage.to.VolumeObjectTO";
public const string TemplateObjectTO = "org.apache.cloudstack.storage.to.TemplateObjectTO";
public const string PrimaryDataStoreTO = "org.apache.cloudstack.storage.to.PrimaryDataStoreTO";
public const string AttachAnswer = "org.apache.cloudstack.storage.command.AttachAnswer";
public const string AttachCommand = "org.apache.cloudstack.storage.command.AttachCommand";
public const string AttachPrimaryDataStoreAnswer = "org.apache.cloudstack.storage.command.AttachPrimaryDataStoreAnswer";
public const string AttachPrimaryDataStoreCmd = "org.apache.cloudstack.storage.command.AttachPrimaryDataStoreCmd";
public const string CopyCmdAnswer = "org.apache.cloudstack.storage.command.CopyCmdAnswer";
public const string CopyCommand = "org.apache.cloudstack.storage.command.CopyCommand";
public const string CreateObjectAnswer = "org.apache.cloudstack.storage.command.CreateObjectAnswer";
public const string CreateObjectCommand = "org.apache.cloudstack.storage.command.CreateObjectCommand";
public const string DeleteCommand = "org.apache.cloudstack.storage.command.DeleteCommand";
public const string DettachAnswer = "org.apache.cloudstack.storage.command.DettachAnswer";
public const string DettachCommand = "org.apache.cloudstack.storage.command.DettachCommand";
}
}

View File

@ -0,0 +1,103 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{C963DFFF-65BA-4E71-ADA5-526A4DA4E0B2}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>HypervResource</RootNamespace>
<AssemblyName>HypervResource</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\</SolutionDir>
<RestorePackages>true</RestorePackages>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'NoUnitTestsDebug|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\NoUnitTestsDebug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'NoUnitTests|AnyCPU'">
<OutputPath>bin\NoUnitTests\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
<Reference Include="AWSSDK">
<HintPath>..\packages\AWSSDK.1.5.23.0\lib\AWSSDK.dll</HintPath>
</Reference>
<Reference Include="Ionic.Zip">
<HintPath>..\packages\DotNetZip.1.9.1.8\lib\net20\Ionic.Zip.dll</HintPath>
</Reference>
<Reference Include="log4net">
<HintPath>..\packages\log4net.2.0.0\lib\net40-full\log4net.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json">
<HintPath>..\packages\Newtonsoft.Json.4.5.11\lib\net40\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Management" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Web" />
<Reference Include="System.Web.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="CloudStackTypes.cs" />
<Compile Include="WmiCallsV2.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="HypervResourceController.cs" />
<Compile Include="Utils.cs" />
<Compile Include="WmiCalls.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\WmiWrappers\WmiWrappers.csproj">
<Project>{db824727-bdc3-437c-a364-7a811d8a160f}</Project>
<Name>WmiWrappers</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("HypervResource")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HypervResource")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f1eb80c1-36fb-438c-a70d-0de5d5e295fb")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -0,0 +1,110 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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.
using log4net;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
namespace HypervResource
{
public class Utils
{
private static ILog s_logger = LogManager.GetLogger(typeof(Utils));
/// <summary>
/// Associate CloudStack object's content with a fully qualified type name.
/// </summary>
/// <param name="objType">Fully qualified type name, e.g. "org.apache.cloudstack.storage.to.TemplateObjectTO"</param>
/// <param name="objValue">Object's data, can be an anonymous object, e.g. </param>
/// <returns></returns>
public static JObject CreateCloudStackObject(string objType, object objValue)
{
JToken objContent = JToken.FromObject(objValue);
JProperty objTypeValuePairing = new JProperty(objType, objContent);
return new JObject(objTypeValuePairing);
}
/// <summary>
/// Copy file on network share to local volume.
/// </summary>
/// <remarks>
/// Access to the network share is acheived by logging into the domain corresponding to the user credentials provided.
/// Windows impersonation does not suffice, because impersonation is limited to domains with an established trust relationship.
/// We have had to import Win32 API calls to allow login. There are a number of examples online. We follow the
/// one at http://stackoverflow.com/a/2541569/939250 </remarks>
/// <param name="filePathRelativeToShare"></param>
/// <param name="cifsShareDetails"></param>
/// <param name="destFile"></param>
public static void DownloadCifsFileToLocalFile(string filePathRelativeToShare, NFSTO cifsShareDetails, string destFile)
{
try
{
IntPtr token = IntPtr.Zero;
bool isSuccess = LogonUser(cifsShareDetails.User, cifsShareDetails.Domain, cifsShareDetails.Password, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref token);
using (WindowsImpersonationContext remoteIdentity = new WindowsIdentity(token).Impersonate())
{
String dest = Path.Combine(cifsShareDetails.UncPath, filePathRelativeToShare);
s_logger.Info(CloudStackTypes.CopyCommand + ": copy " + Path.Combine(cifsShareDetails.UncPath, filePathRelativeToShare) + " to " + destFile);
File.Copy(dest, destFile, true);
remoteIdentity.Undo();
}
}
catch (UnauthorizedAccessException ex)
{
string errMsg = "Invalid user or password for the share " + cifsShareDetails.UncPath;
s_logger.Error(errMsg);
throw new ArgumentException(errMsg, ex);
}
}
// from http://stackoverflow.com/a/2541569/939250
#region imports
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool CloseHandle(IntPtr handle);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public extern static bool DuplicateToken(IntPtr existingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, ref IntPtr duplicateTokenHandle);
#endregion
#region logon consts
// logon types
const int LOGON32_LOGON_INTERACTIVE = 2;
const int LOGON32_LOGON_NETWORK = 3;
const int LOGON32_LOGON_NEW_CREDENTIALS = 9;
// logon providers
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_PROVIDER_WINNT50 = 3;
const int LOGON32_PROVIDER_WINNT40 = 2;
const int LOGON32_PROVIDER_WINNT35 = 1;
#endregion
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,500 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2;
using log4net;
using System.Globalization;
using System.Management;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using CloudStack.Plugin.WmiWrappers.ROOT.CIMV2;
using System.IO;
namespace HypervResource
{
public class WmiCallsV2
{
public static String CloudStackUserDataKey = "cloudstack-vm-userdata";
public static void Initialize()
{
// Trigger assembly load into curren appdomain
}
private static ILog logger = LogManager.GetLogger(typeof(WmiCallsV2));
/// <summary>
/// Returns ComputerSystem lacking any NICs and VOLUMEs
/// </summary>
public static ComputerSystem AddUserData(ComputerSystem vm, string userData)
{
// Obtain controller for Hyper-V virtualisation subsystem
VirtualSystemManagementService vmMgmtSvc = GetVirtualisationSystemManagementService();
// Create object to hold the data.
KvpExchangeDataItem kvpItem = KvpExchangeDataItem.CreateInstance();
kvpItem.LateBoundObject["Name"] = WmiCallsV2.CloudStackUserDataKey;
kvpItem.LateBoundObject["Data"] = userData;
kvpItem.LateBoundObject["Source"] = 0;
logger.Debug("VM " + vm.Name + " gets userdata " + userData);
// Update the resource settings for the VM.
System.Management.ManagementBaseObject kvpMgmtObj = kvpItem.LateBoundObject;
System.Management.ManagementPath jobPath;
String kvpStr = kvpMgmtObj.GetText(System.Management.TextFormat.CimDtd20);
uint ret_val = vmMgmtSvc.AddKvpItems(new String[] { kvpStr }, vm.Path, out jobPath);
// If the Job is done asynchronously
if (ret_val == ReturnCode.Started)
{
JobCompleted(jobPath);
}
else if (ret_val != ReturnCode.Completed)
{
var errMsg = string.Format(
"Failed to update VM {0} (GUID {1}) due to {2} (ModifyVirtualSystem call), existing VM not deleted",
vm.ElementName,
vm.Name,
ReturnCode.ToString(ret_val));
var ex = new WmiException(errMsg);
logger.Error(errMsg, ex);
throw ex;
}
return vm;
}
/// <summary>
/// Returns ComputerSystem lacking any NICs and VOLUMEs
/// </summary>
public static void DeleteHostKvpItem(ComputerSystem vm, string key)
{
// Obtain controller for Hyper-V virtualisation subsystem
VirtualSystemManagementService vmMgmtSvc = GetVirtualisationSystemManagementService();
// Create object to hold the data.
KvpExchangeDataItem kvpItem = KvpExchangeDataItem.CreateInstance();
kvpItem.LateBoundObject["Name"] = WmiCallsV2.CloudStackUserDataKey;
kvpItem.LateBoundObject["Data"] = "dummy";
kvpItem.LateBoundObject["Source"] = 0;
logger.Debug("VM " + vm.Name + " will have KVP key " + key + " removed.");
String kvpStr = kvpItem.LateBoundObject.GetText(TextFormat.CimDtd20);
// Update the resource settings for the VM.
ManagementPath jobPath;
uint ret_val = vmMgmtSvc.RemoveKvpItems(new String[] { kvpStr }, vm.Path, out jobPath);
// If the Job is done asynchronously
if (ret_val == ReturnCode.Started)
{
JobCompleted(jobPath);
}
else if (ret_val != ReturnCode.Completed)
{
var errMsg = string.Format(
"Failed to update VM {0} (GUID {1}) due to {2} (ModifyVirtualSystem call), existing VM not deleted",
vm.ElementName,
vm.Name,
ReturnCode.ToString(ret_val));
var ex = new WmiException(errMsg);
logger.Error(errMsg, ex);
throw ex;
}
}
public static VirtualSystemManagementService GetVirtualisationSystemManagementService()
{
// VirtualSystemManagementService is a singleton, most anonymous way of lookup is by asking for the set
// of local instances, which should be size 1.
var virtSysMgmtSvcCollection = VirtualSystemManagementService.GetInstances();
foreach (VirtualSystemManagementService item in virtSysMgmtSvcCollection)
{
return item;
}
var errMsg = string.Format("No Hyper-V subsystem on server");
var ex = new WmiException(errMsg);
logger.Error(errMsg, ex);
throw ex;
}
/// <summary>
/// Similar to http://msdn.microsoft.com/en-us/library/hh850031%28v=vs.85%29.aspx
/// </summary>
/// <param name="jobPath"></param>
/// <returns></returns>
private static void JobCompleted(ManagementPath jobPath)
{
ConcreteJob jobObj = null;
for(;;)
{
jobObj = new ConcreteJob(jobPath);
if (jobObj.JobState != JobState.Starting && jobObj.JobState != JobState.Running)
{
break;
}
logger.InfoFormat("In progress... {0}% completed.", jobObj.PercentComplete);
System.Threading.Thread.Sleep(1000);
}
if (jobObj.JobState != JobState.Completed)
{
var errMsg = string.Format(
"Hyper-V Job failed, Error Code:{0}, Description: {1}",
jobObj.ErrorCode,
jobObj.ErrorDescription);
var ex = new WmiException(errMsg);
logger.Error(errMsg, ex);
throw ex;
}
logger.DebugFormat("WMI job succeeded: {0}, Elapsed={1}", jobObj.Description, jobObj.ElapsedTime);
}
public static ComputerSystem GetComputerSystem(string displayName)
{
var wmiQuery = String.Format("ElementName=\"{0}\"", displayName);
ComputerSystem.ComputerSystemCollection vmCollection = ComputerSystem.GetInstances(wmiQuery);
// Return the first one
foreach (ComputerSystem vm in vmCollection)
{
return vm;
}
return null;
}
public static List<string> GetVmElementNames()
{
List<string> result = new List<string>();
ComputerSystem.ComputerSystemCollection vmCollection = ComputerSystem.GetInstances();
// Return the first one
foreach (ComputerSystem vm in vmCollection)
{
if (vm.Caption.StartsWith("Hosting Computer System") )
{
continue;
}
result.Add(vm.ElementName);
}
return result;
}
public static VirtualSystemSettingData GetVmSettings(ComputerSystem vm)
{
// An ASSOCIATOR object provides the cross reference from the ComputerSettings and the
// VirtualSystemSettingData, but generated wrappers do not expose a ASSOCIATOR OF query as a method.
// Instead, we use the System.Management to code the equivalant of
// string query = string.Format( "ASSOCIATORS OF {{{0}}} WHERE ResultClass = {1}", vm.path, resultclassName);
//
var wmiObjQuery = new RelatedObjectQuery(vm.Path.Path, VirtualSystemSettingData.CreatedClassName);
// NB: default scope of ManagementObjectSearcher is '\\.\root\cimv2', which does not contain
// the virtualisation objects.
var wmiObjectSearch = new ManagementObjectSearcher(vm.Scope, wmiObjQuery);
var wmiObjCollection = new VirtualSystemSettingData.VirtualSystemSettingDataCollection(wmiObjectSearch.Get());
// When snapshots are taken into account, there can be multiple settings objects
// take the first one that isn't a snapshot
foreach (VirtualSystemSettingData wmiObj in wmiObjCollection)
{
if (wmiObj.VirtualSystemType == "Microsoft:Hyper-V:System:Realized" ||
wmiObj.VirtualSystemType == "Microsoft:Hyper-V:System:Planned")
{
return wmiObj;
}
}
var errMsg = string.Format("No VirtualSystemSettingData for VM {0}, path {1}", vm.ElementName, vm.Path.Path);
var ex = new WmiException(errMsg);
logger.Error(errMsg, ex);
throw ex;
}
public static KvpExchangeComponentSettingData GetKvpSettings(VirtualSystemSettingData vmSettings)
{
// An ASSOCIATOR object provides the cross reference from the VirtualSystemSettingData and the
// KvpExchangeComponentSettingData, but generated wrappers do not expose a ASSOCIATOR OF query as a method.
// Instead, we use the System.Management to code the equivalant of
// string query = string.Format( "ASSOCIATORS OF {{{0}}} WHERE ResultClass = {1}", vmSettings.path, resultclassName);
//
var wmiObjQuery = new RelatedObjectQuery(vmSettings.Path.Path, KvpExchangeComponentSettingData.CreatedClassName);
// NB: default scope of ManagementObjectSearcher is '\\.\root\cimv2', which does not contain
// the virtualisation objects.
var wmiObjectSearch = new ManagementObjectSearcher(vmSettings.Scope, wmiObjQuery);
var wmiObjCollection = new KvpExchangeComponentSettingData.KvpExchangeComponentSettingDataCollection(wmiObjectSearch.Get());
foreach (KvpExchangeComponentSettingData wmiObj in wmiObjCollection)
{
return wmiObj;
}
var errMsg = string.Format("No KvpExchangeComponentSettingData in VirtualSystemSettingData {0}", vmSettings.Path.Path);
var ex = new WmiException(errMsg);
logger.Error(errMsg, ex);
throw ex;
}
}
public class WmiException : Exception
{
public WmiException()
{
}
public WmiException(string message)
: base(message)
{
}
public WmiException(string message, Exception inner)
: base(message, inner)
{
}
}
/// <summary>
/// Covers V2 API, see
/// http://msdn.microsoft.com/en-us/library/hh850031%28v=vs.85%29.aspx
/// </summary>
public static class ReturnCode
{
public const UInt32 Completed = 0;
public const UInt32 Started = 4096;
public const UInt32 Failed = 32768;
public const UInt32 AccessDenied = 32769;
public const UInt32 NotSupported = 32770;
public const UInt32 Unknown = 32771;
public const UInt32 Timeout = 32772;
public const UInt32 InvalidParameter = 32773;
public const UInt32 SystemInUse = 32774;
public const UInt32 InvalidState = 32775;
public const UInt32 IncorrectDataType = 32776;
public const UInt32 SystemNotAvailable = 32777;
public const UInt32 OutofMemory = 32778;
public static string ToString(UInt32 value)
{
string result = "Unknown return code";
switch (value)
{
case Completed: result = "Completed"; break;
case Started: result = "Started"; break;
case Failed: result = "Failed"; break;
case AccessDenied: result = "AccessDenied"; break;
case NotSupported: result = "NotSupported"; break;
case Unknown: result = "Unknown"; break;
case Timeout: result = "Timeout"; break;
case InvalidParameter: result = "InvalidParameter"; break;
case SystemInUse: result = "SystemInUse"; break;
case InvalidState: result = "InvalidState"; break;
case IncorrectDataType: result = "IncorrectDataType"; break;
case SystemNotAvailable: result = "SystemNotAvailable"; break;
case OutofMemory: result = "OutofMemory"; break;
}
return result;
}
}
/// <summary>
/// Covers V2 API, see
/// http://msdn.microsoft.com/en-us/library/hh850031%28v=vs.85%29.aspx
/// </summary>
public static class JobState
{
public const UInt16 New = 2;
public const UInt16 Starting = 3;
public const UInt16 Running = 4;
public const UInt16 Suspended = 5;
public const UInt16 ShuttingDown = 6;
public const UInt16 Completed = 7;
public const UInt16 Terminated = 8;
public const UInt16 Killed = 9;
public const UInt16 Exception = 10;
public const UInt16 Service = 11;
public static string ToString(UInt16 value)
{
string result = "Unknown JobState code";
switch (value)
{
case New: result = "New"; break;
case Starting: result = "Starting"; break;
case Running: result = "Running"; break;
case Suspended: result = "Suspended"; break;
case ShuttingDown: result = "ShuttingDown"; break;
case Completed: result = "Completed"; break;
case Terminated: result = "Terminated"; break;
case Killed: result = "Killed"; break;
case Exception: result = "Exception"; break;
case Service: result = "Service"; break;
}
return result;
}
}
/// <summary>
/// V2 API (see http://msdn.microsoft.com/en-us/library/hh850279(v=vs.85).aspx)
/// has removed 'Paused' and 'Suspended' as compared to the
/// V1 API (see http://msdn.microsoft.com/en-us/library/cc723874%28v=vs.85%29.aspx)
/// However, Paused and Suspended appear on the VM state transition table
/// (see http://msdn.microsoft.com/en-us/library/hh850116(v=vs.85).aspx#methods)
/// </summary>
public class RequiredState
{
public const UInt16 Enabled = 2; // Turns the VM on.
public const UInt16 Disabled = 3; // Turns the VM off.
public const UInt16 ShutDown = 4;
public const UInt16 Offline = 6;
public const UInt16 Test = 7;
public const UInt16 Defer = 8;
public const UInt16 Quiesce = 9;
public const UInt16 Reboot = 10; // A hard reset of the VM.
public const UInt16 Reset = 11; // For future use.
public const UInt16 Paused = 32768; // Pauses the VM.
public const UInt16 Suspended = 32769; // Saves the state of the VM.
public static string ToString(UInt16 value)
{
string result = "Unknown RequiredState code";
switch (value)
{
case Enabled: result = "Enabled"; break;
case Disabled: result = "Disabled"; break;
case ShutDown: result = "ShutDown"; break;
case Offline: result = "Offline"; break;
case Test: result = "Test"; break;
case Defer: result = "Defer"; break;
case Quiesce: result = "Quiesce"; break;
case Reboot: result = "Reboot"; break;
case Reset: result = "Reset"; break;
}
return result;
}
}
/// <summary>
/// V2 API specifies the states below in its state transition graph at
/// http://msdn.microsoft.com/en-us/library/hh850116(v=vs.85).aspx#methods
/// However, the CIM standard has additional possibilities based on the description
/// of EnabledState.
/// The previous V1 API is described by
/// http://msdn.microsoft.com/en-us/library/cc136822%28v=vs.85%29.aspx
/// </summary>
public class EnabledState
{
/// <summary>
/// The state of the VM could not be determined.
/// </summary>
public const UInt16 Unknown = 0;
/// <summary>
/// The VM is running.
/// </summary>
public const UInt16 Enabled = 2;
/// <summary>
/// The VM is turned off.
/// </summary>
public const UInt16 Disabled = 3;
/// <summary>
/// The VM is paused.
/// </summary>
public const UInt16 Paused = 32768;
/// <summary>
/// The VM is in a saved state.
/// </summary>
public const UInt16 Suspended = 32769;
/// <summary>
/// The VM is starting. This is a transitional state between 3 (Disabled)
/// or 32769 (Suspended) and 2 (Enabled) initiated by a call to the
/// RequestStateChange method with a RequestedState parameter of 2 (Enabled).
/// </summary>
public const UInt16 Starting = 32770;
/// <summary>
/// Starting with Windows Server 2008 R2 this value is not supported.
/// If the VM is performing a snapshot operation, the element at index 1
/// of the OperationalStatus property array will contain 32768 (Creating Snapshot),
/// 32769 (Applying Snapshot), or 32770 (Deleting Snapshot).
/// </summary>
public const UInt16 Snapshotting = 32771;
/// <summary>
/// The VM is saving its state. This is a transitional state between 2 (Enabled)
/// and 32769 (Suspended) initiated by a call to the RequestStateChange method
/// with a RequestedState parameter of 32769 (Suspended).
/// </summary>
public const UInt16 Saving = 32773;
/// <summary>
/// The VM is turning off. This is a transitional state between 2 (Enabled)
/// and 3 (Disabled) initiated by a call to the RequestStateChange method
/// with a RequestedState parameter of 3 (Disabled) or a guest operating system
/// initiated power off.
/// </summary>
public const UInt16 Stopping = 32774;
/// <summary>
/// The VM is pausing. This is a transitional state between 2 (Enabled) and 32768 (Paused) initiated by a call to the RequestStateChange method with a RequestedState parameter of 32768 (Paused).
/// </summary>
public const UInt16 Pausing = 32776;
/// <summary>
/// The VM is resuming from a paused state. This is a transitional state between 32768 (Paused) and 2 (Enabled).
/// </summary>
public const UInt16 Resuming = 32777;
public static string ToString(UInt16 value)
{
string result = "Unknown";
switch (value)
{
case Enabled: result = "Enabled"; break;
case Disabled: result = "Disabled"; break;
case Paused: result = "Paused"; break;
case Suspended: result = "Suspended"; break;
case Starting: result = "Starting"; break;
case Snapshotting: result = "Snapshotting"; break; // NOT used
case Saving: result = "Saving"; break;
case Stopping: result = "Stopping"; break;
case Pausing: result = "Pausing"; break;
case Resuming: result = "Resuming"; break;
}
return result;
}
public static string ToCloudStackState(UInt16 value)
{
string result = "Unknown";
switch (value)
{
case Enabled: result = "Running"; break;
case Disabled: result = "Stopped"; break;
case Paused: result = "Unknown"; break;
case Suspended: result = "Unknown"; break;
case Starting: result = "Starting"; break;
case Snapshotting: result = "Unknown"; break; // NOT used
case Saving: result = "Saving"; break;
case Stopping: result = "Stopping"; break;
case Pausing: result = "Unknown"; break;
case Resuming: result = "Starting"; break;
}
return result;
}
}
}

View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="AWSSDK" version="1.5.23.0" targetFramework="net45" />
<package id="DotNetZip" version="1.9.1.8" targetFramework="net45" />
<package id="log4net" version="2.0.0" targetFramework="net45" />
<package id="Newtonsoft.Json" version="4.5.11" targetFramework="net45" />
</packages>

View File

@ -0,0 +1,128 @@
<?xml version="1.0" encoding="utf-8" ?>
<!--
Note: Add entries to the App.config file for configuration settings
that apply only to the Test project.
-->
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="CloudStack.Plugin.AgentShell.AgentSettings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="CloudStack.Plugin.AgentShell.AgentSettings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<appSettings>
</appSettings>
<connectionStrings>
</connectionStrings>
<applicationSettings>
<CloudStack.Plugin.AgentShell.AgentSettings>
<setting name="cpus" serializeAs="String">
<value>8</value>
</setting>
<setting name="private_ip_address" serializeAs="String">
<value>10.1.1.1</value>
</setting>
<setting name="type" serializeAs="String">
<value>Routing</value>
</setting>
<setting name="local_storage_uuid" serializeAs="String">
<value>5fe2bad3-d785-394e-9949-89786b8a63d2</value>
</setting>
<setting name="capabilities" serializeAs="String">
<value>hvm</value>
</setting>
<setting name="Settingcpuspeed" serializeAs="String">
<value>2130</value>
</setting>
<setting name="port" serializeAs="String">
<value>8250</value>
</setting>
<setting name="memory" serializeAs="String">
<value>34359738368</value>
</setting>
<setting name="host" serializeAs="String">
<value>camldonall01.citrite.net</value>
</setting>
<setting name="pod" serializeAs="String">
<value>1</value>
</setting>
<setting name="gateway_ip_address" serializeAs="String">
<value>10.70.176.1</value>
</setting>
<setting name="cluster" serializeAs="String">
<value>2</value>
</setting>
<setting name="zone" serializeAs="String">
<value>1</value>
</setting>
<setting name="local_storage_path" serializeAs="String">
<value>E:\Disks\Disks</value>
</setting>
<setting name="workers" serializeAs="String">
<value>5</value>
</setting>
<setting name="private_ip_netmask" serializeAs="String">
<value>255.255.240.0</value>
</setting>
<setting name="RootDeviceReservedSpaceBytes" serializeAs="String">
<value>4294967296</value>
</setting>
<setting name="hyperv_plugin_root" serializeAs="String">
<value>..\..\..\..\..\</value>
</setting>
<setting name="RootDeviceName" serializeAs="String">
<value>e:\</value>
</setting>
<setting name="dom0MinMemory" serializeAs="String">
<value>2048</value>
</setting>
<setting name="private_mac_address" serializeAs="String">
<value>101F742C6B88</value>
</setting>
</CloudStack.Plugin.AgentShell.AgentSettings>
</applicationSettings>
<userSettings>
<CloudStack.Plugin.AgentShell.AgentSettings>
<setting name="local_secondary_storage_path" serializeAs="String">
<value>c:\Secondary</value>
</setting>
<setting name="local_storage_path" serializeAs="String">
<value>E:\Disks\Disks</value>
</setting>
<setting name="testLocalStoreUUID" serializeAs="String">
<value>5fe2bad3-d785-394e-9949-89786b8a63d2</value>
</setting>
<setting name="testLocalStorePath" serializeAs="String">
<value>.\var\test\storagepool</value>
</setting>
<setting name="testS3Bucket" serializeAs="String">
<value>cshv3eu</value>
</setting>
<setting name="testS3Endpoint" serializeAs="String">
<value>s3.amazonaws.com</value>
</setting>
<setting name="testS3AccessKey" serializeAs="String">
<value>testS3AccessKey</value>
</setting>
<setting name="testS3SecretKey" serializeAs="String">
<value>testS3SecretKey</value>
</setting>
<setting name="testS3TemplateName" serializeAs="String">
<value>206-2-73592258-559a-3b38-8f66-b667aab143eb</value>
</setting>
<setting name="testCifsTemplateName" serializeAs="String">
<value>206-2-73592258-559a-3b38-8f66-b667aab143eb</value>
</setting>
<setting name="testCifsUrl" serializeAs="String">
<value>cifs://10.1.1.1/secondary?user\u003dadministrator\u0026password\u003d1pass%40word1</value>
</setting>
<setting name="testCifsPath" serializeAs="String">
<value>template/tmpl/2/201/6dda6631-4daa-3150-a49a-d5a4b0a4c4b6.vhd</value>
</setting>
</CloudStack.Plugin.AgentShell.AgentSettings>
</userSettings>
</configuration>

View File

@ -0,0 +1,35 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ServerResource.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ServerResource.Tests")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("727beb1c-6e7c-49b2-8fbd-f03dbe481b08")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -0,0 +1,124 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>
</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{925FD1DE-6211-4E10-9949-3751B8ABDF59}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>ServerResource.Tests</RootNamespace>
<AssemblyName>ServerResource.Tests</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\</SolutionDir>
<RestorePackages>true</RestorePackages>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'NoUnitTestsDebug|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\NoUnitTestsDebug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'NoUnitTests|AnyCPU'">
<OutputPath>bin\NoUnitTests\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
<Reference Include="Ionic.Zip">
<HintPath>..\packages\DotNetZip.1.9.1.8\lib\net20\Ionic.Zip.dll</HintPath>
</Reference>
<Reference Include="log4net">
<HintPath>..\packages\log4net.2.0.0\lib\net40-full\log4net.dll</HintPath>
</Reference>
<Reference Include="Microsoft.CSharp" />
<Reference Include="Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" />
<Reference Include="Newtonsoft.Json">
<HintPath>..\packages\Newtonsoft.Json.4.5.11\lib\net40\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
<Reference Include="System.Data" />
<Reference Include="System.Management" />
<Reference Include="System.ServiceProcess" />
<Reference Include="System.Web" />
<Reference Include="System.Web.ApplicationServices" />
<Reference Include="System.Web.Extensions" />
<Reference Include="System.Web.Abstractions" />
<Reference Include="System.Web.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
<Reference Include="System.Web.Routing" />
<Reference Include="System.Xml" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Net.Http">
</Reference>
<Reference Include="System.Net.Http.WebRequest">
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="HypervResourceControllerTest.cs" />
</ItemGroup>
<ItemGroup>
<Content Include="App.config">
<SubType>Designer</SubType>
</Content>
</ItemGroup>
<ItemGroup>
<None Include="packages.config">
<SubType>Designer</SubType>
</None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\AgentShell\AgentShell.csproj">
<Project>{9060b539-62d0-4e71-a6c6-5944828774e9}</Project>
<Name>AgentShell</Name>
</ProjectReference>
<ProjectReference Include="..\HypervResource\HypervResource.csproj">
<Project>{c963dfff-65ba-4e71-ada5-526a4da4e0b2}</Project>
<Name>HypervResource</Name>
</ProjectReference>
<ProjectReference Include="..\WmiWrappers\WmiWrappers.csproj">
<Project>{db824727-bdc3-437c-a364-7a811d8a160f}</Project>
<Name>WmiWrappers</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="DotNetZip" version="1.9.1.8" targetFramework="net45" />
<package id="log4net" version="2.0.0" targetFramework="net45" />
<package id="Newtonsoft.Json" version="4.5.11" targetFramework="net45" />
</packages>

View File

@ -0,0 +1,61 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2012
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ServerResource.Tests", "ServerResource.Tests\ServerResource.Tests.csproj", "{925FD1DE-6211-4E10-9949-3751B8ABDF59}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AgentShell", "AgentShell\AgentShell.csproj", "{9060B539-62D0-4E71-A6C6-5944828774E9}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WmiWrappers", "WmiWrappers\WmiWrappers.csproj", "{DB824727-BDC3-437C-A364-7A811D8A160F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HypervResource", "HypervResource\HypervResource.csproj", "{C963DFFF-65BA-4E71-ADA5-526A4DA4E0B2}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{3481E04E-4BB9-4E0B-94A9-DB70A4F4D218}"
ProjectSection(SolutionItems) = preProject
.nuget\NuGet.Config = .nuget\NuGet.Config
.nuget\NuGet.exe = .nuget\NuGet.exe
.nuget\NuGet.targets = .nuget\NuGet.targets
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
NoUnitTests|Any CPU = NoUnitTests|Any CPU
NoUnitTestsDebug|Any CPU = NoUnitTestsDebug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{925FD1DE-6211-4E10-9949-3751B8ABDF59}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{925FD1DE-6211-4E10-9949-3751B8ABDF59}.Debug|Any CPU.Build.0 = Debug|Any CPU
{925FD1DE-6211-4E10-9949-3751B8ABDF59}.NoUnitTests|Any CPU.ActiveCfg = NoUnitTests|Any CPU
{925FD1DE-6211-4E10-9949-3751B8ABDF59}.NoUnitTestsDebug|Any CPU.ActiveCfg = NoUnitTestsDebug|Any CPU
{925FD1DE-6211-4E10-9949-3751B8ABDF59}.Release|Any CPU.ActiveCfg = Release|Any CPU
{925FD1DE-6211-4E10-9949-3751B8ABDF59}.Release|Any CPU.Build.0 = Release|Any CPU
{9060B539-62D0-4E71-A6C6-5944828774E9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9060B539-62D0-4E71-A6C6-5944828774E9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9060B539-62D0-4E71-A6C6-5944828774E9}.NoUnitTests|Any CPU.ActiveCfg = NoUnitTests|Any CPU
{9060B539-62D0-4E71-A6C6-5944828774E9}.NoUnitTests|Any CPU.Build.0 = NoUnitTests|Any CPU
{9060B539-62D0-4E71-A6C6-5944828774E9}.NoUnitTestsDebug|Any CPU.ActiveCfg = NoUnitTestsDebug|Any CPU
{9060B539-62D0-4E71-A6C6-5944828774E9}.NoUnitTestsDebug|Any CPU.Build.0 = NoUnitTestsDebug|Any CPU
{9060B539-62D0-4E71-A6C6-5944828774E9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9060B539-62D0-4E71-A6C6-5944828774E9}.Release|Any CPU.Build.0 = Release|Any CPU
{DB824727-BDC3-437C-A364-7A811D8A160F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{DB824727-BDC3-437C-A364-7A811D8A160F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DB824727-BDC3-437C-A364-7A811D8A160F}.NoUnitTests|Any CPU.ActiveCfg = NoUnitTests|Any CPU
{DB824727-BDC3-437C-A364-7A811D8A160F}.NoUnitTests|Any CPU.Build.0 = NoUnitTests|Any CPU
{DB824727-BDC3-437C-A364-7A811D8A160F}.NoUnitTestsDebug|Any CPU.ActiveCfg = NoUnitTestsDebug|Any CPU
{DB824727-BDC3-437C-A364-7A811D8A160F}.NoUnitTestsDebug|Any CPU.Build.0 = NoUnitTestsDebug|Any CPU
{DB824727-BDC3-437C-A364-7A811D8A160F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DB824727-BDC3-437C-A364-7A811D8A160F}.Release|Any CPU.Build.0 = Release|Any CPU
{C963DFFF-65BA-4E71-ADA5-526A4DA4E0B2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C963DFFF-65BA-4E71-ADA5-526A4DA4E0B2}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C963DFFF-65BA-4E71-ADA5-526A4DA4E0B2}.NoUnitTests|Any CPU.ActiveCfg = NoUnitTests|Any CPU
{C963DFFF-65BA-4E71-ADA5-526A4DA4E0B2}.NoUnitTests|Any CPU.Build.0 = NoUnitTests|Any CPU
{C963DFFF-65BA-4E71-ADA5-526A4DA4E0B2}.NoUnitTestsDebug|Any CPU.ActiveCfg = NoUnitTestsDebug|Any CPU
{C963DFFF-65BA-4E71-ADA5-526A4DA4E0B2}.NoUnitTestsDebug|Any CPU.Build.0 = NoUnitTestsDebug|Any CPU
{C963DFFF-65BA-4E71-ADA5-526A4DA4E0B2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C963DFFF-65BA-4E71-ADA5-526A4DA4E0B2}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("WmiWrappers")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WmiWrappers")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e78f4bad-16a9-4e0e-8f46-083c093492db")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -0,0 +1,976 @@
namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION {
using System;
using System.ComponentModel;
using System.Management;
using System.Collections;
using System.Globalization;
using System.ComponentModel.Design.Serialization;
using System.Reflection;
// Functions ShouldSerialize<PropertyName> are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use Is<PropertyName>Null function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio.
// Functions Is<PropertyName>Null() are used to check if a property is NULL.
// Functions Reset<PropertyName> are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL.
// Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used.
// An Early Bound class generated for the WMI class.Msvm_ResourceAllocationSettingData
public class ResourceAllocationSettingData : System.ComponentModel.Component {
// Private property to hold the WMI namespace in which the class resides.
private static string CreatedWmiNamespace = "ROOT\\virtualization";
// Private property to hold the name of WMI class which created this class.
public static string CreatedClassName = "Msvm_ResourceAllocationSettingData";
// Private member variable to hold the ManagementScope which is used by the various methods.
private static System.Management.ManagementScope statMgmtScope = null;
private ManagementSystemProperties PrivateSystemProperties;
// Underlying lateBound WMI object.
private System.Management.ManagementObject PrivateLateBoundObject;
// Member variable to store the 'automatic commit' behavior for the class.
private bool AutoCommitProp;
// Private variable to hold the embedded property representing the instance.
private System.Management.ManagementBaseObject embeddedObj;
// The current WMI object used
private System.Management.ManagementBaseObject curObj;
// Flag to indicate if the instance is an embedded object.
private bool isEmbedded;
// Below are different overloads of constructors to initialize an instance of the class with a WMI object.
public ResourceAllocationSettingData() {
this.InitializeObject(null, null, null);
}
public ResourceAllocationSettingData(string keyInstanceID) {
this.InitializeObject(null, new System.Management.ManagementPath(ResourceAllocationSettingData.ConstructPath(keyInstanceID)), null);
}
public ResourceAllocationSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) {
this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(ResourceAllocationSettingData.ConstructPath(keyInstanceID)), null);
}
public ResourceAllocationSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) {
this.InitializeObject(null, path, getOptions);
}
public ResourceAllocationSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) {
this.InitializeObject(mgmtScope, path, null);
}
public ResourceAllocationSettingData(System.Management.ManagementPath path) {
this.InitializeObject(null, path, null);
}
public ResourceAllocationSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) {
this.InitializeObject(mgmtScope, path, getOptions);
}
public ResourceAllocationSettingData(System.Management.ManagementObject theObject) {
Initialize();
if ((CheckIfProperClass(theObject) == true)) {
PrivateLateBoundObject = theObject;
PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject);
curObj = PrivateLateBoundObject;
}
else {
throw new System.ArgumentException("Class name does not match.");
}
}
public ResourceAllocationSettingData(System.Management.ManagementBaseObject theObject) {
Initialize();
if ((CheckIfProperClass(theObject) == true)) {
embeddedObj = theObject;
PrivateSystemProperties = new ManagementSystemProperties(theObject);
curObj = embeddedObj;
isEmbedded = true;
}
else {
throw new System.ArgumentException("Class name does not match.");
}
}
// Property returns the namespace of the WMI class.
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string OriginatingNamespace {
get {
return "ROOT\\virtualization";
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string ManagementClassName {
get {
string strRet = CreatedClassName;
if ((curObj != null)) {
if ((curObj.ClassPath != null)) {
strRet = ((string)(curObj["__CLASS"]));
if (((strRet == null)
|| (strRet == string.Empty))) {
strRet = CreatedClassName;
}
}
}
return strRet;
}
}
// Property pointing to an embedded object to get System properties of the WMI object.
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public ManagementSystemProperties SystemProperties {
get {
return PrivateSystemProperties;
}
}
// Property returning the underlying lateBound object.
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public System.Management.ManagementBaseObject LateBoundObject {
get {
return curObj;
}
}
// ManagementScope of the object.
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public System.Management.ManagementScope Scope {
get {
if ((isEmbedded == false)) {
return PrivateLateBoundObject.Scope;
}
else {
return null;
}
}
set {
if ((isEmbedded == false)) {
PrivateLateBoundObject.Scope = value;
}
}
}
// Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property).
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool AutoCommit {
get {
return AutoCommitProp;
}
set {
AutoCommitProp = value;
}
}
// The ManagementPath of the underlying WMI object.
[Browsable(true)]
public System.Management.ManagementPath Path {
get {
if ((isEmbedded == false)) {
return PrivateLateBoundObject.Path;
}
else {
return null;
}
}
set {
if ((isEmbedded == false)) {
if ((CheckIfProperClass(null, value, null) != true)) {
throw new System.ArgumentException("Class name does not match.");
}
PrivateLateBoundObject.Path = value;
}
}
}
// Public static scope property which is used by the various methods.
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public static System.Management.ManagementScope StaticScope {
get {
return statMgmtScope;
}
set {
statMgmtScope = value;
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string Address {
get {
return ((string)(curObj["Address"]));
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string AllocationUnits {
get {
return ((string)(curObj["AllocationUnits"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsAutomaticAllocationNull {
get {
if ((curObj["AutomaticAllocation"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[TypeConverter(typeof(WMIValueTypeConverter))]
public bool AutomaticAllocation {
get {
if ((curObj["AutomaticAllocation"] == null)) {
return System.Convert.ToBoolean(0);
}
return ((bool)(curObj["AutomaticAllocation"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsAutomaticDeallocationNull {
get {
if ((curObj["AutomaticDeallocation"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[TypeConverter(typeof(WMIValueTypeConverter))]
public bool AutomaticDeallocation {
get {
if ((curObj["AutomaticDeallocation"] == null)) {
return System.Convert.ToBoolean(0);
}
return ((bool)(curObj["AutomaticDeallocation"]));
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string Caption {
get {
return ((string)(curObj["Caption"]));
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string[] Connection {
get {
return ((string[])(curObj["Connection"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsConsumerVisibilityNull {
get {
if ((curObj["ConsumerVisibility"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[TypeConverter(typeof(WMIValueTypeConverter))]
public ushort ConsumerVisibility {
get {
if ((curObj["ConsumerVisibility"] == null)) {
return System.Convert.ToUInt16(0);
}
return ((ushort)(curObj["ConsumerVisibility"]));
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string Description {
get {
return ((string)(curObj["Description"]));
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string ElementName {
get {
return ((string)(curObj["ElementName"]));
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string[] HostResource {
get {
return ((string[])(curObj["HostResource"]));
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string InstanceID {
get {
return ((string)(curObj["InstanceID"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsLimitNull {
get {
if ((curObj["Limit"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[TypeConverter(typeof(WMIValueTypeConverter))]
public ulong Limit {
get {
if ((curObj["Limit"] == null)) {
return System.Convert.ToUInt64(0);
}
return ((ulong)(curObj["Limit"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsMappingBehaviorNull {
get {
if ((curObj["MappingBehavior"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[TypeConverter(typeof(WMIValueTypeConverter))]
public ushort MappingBehavior {
get {
if ((curObj["MappingBehavior"] == null)) {
return System.Convert.ToUInt16(0);
}
return ((ushort)(curObj["MappingBehavior"]));
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string OtherResourceType {
get {
return ((string)(curObj["OtherResourceType"]));
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string Parent {
get {
return ((string)(curObj["Parent"]));
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string PoolID {
get {
return ((string)(curObj["PoolID"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsReservationNull {
get {
if ((curObj["Reservation"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[TypeConverter(typeof(WMIValueTypeConverter))]
public ulong Reservation {
get {
if ((curObj["Reservation"] == null)) {
return System.Convert.ToUInt64(0);
}
return ((ulong)(curObj["Reservation"]));
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string ResourceSubType {
get {
return ((string)(curObj["ResourceSubType"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsResourceTypeNull {
get {
if ((curObj["ResourceType"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[TypeConverter(typeof(WMIValueTypeConverter))]
public ushort ResourceType {
get {
if ((curObj["ResourceType"] == null)) {
return System.Convert.ToUInt16(0);
}
return ((ushort)(curObj["ResourceType"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsVirtualQuantityNull {
get {
if ((curObj["VirtualQuantity"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[TypeConverter(typeof(WMIValueTypeConverter))]
public ulong VirtualQuantity {
get {
if ((curObj["VirtualQuantity"] == null)) {
return System.Convert.ToUInt64(0);
}
return ((ulong)(curObj["VirtualQuantity"]));
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description(@"A free-form string array of identifiers of this resource presented to the virtual computer system's operating system. These values are only used if the ResourceType property is set to 6 (Parallel SCSI HBA) and the ResourceSubType property is set to ""Microsoft Synthetic SCSI Controller"". This property is set to ""GUID"".
This is a read-only property, but it can be changed using the ModifyVirtualSystemResources method of the Msvm_VirtualSystemManagementService class.
Windows Server 2008: The VirtualSystemIdentifiers property is not supported until Windows Server 2008 R2.")]
public string[] VirtualSystemIdentifiers {
get {
return ((string[])(curObj["VirtualSystemIdentifiers"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsWeightNull {
get {
if ((curObj["Weight"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[TypeConverter(typeof(WMIValueTypeConverter))]
public uint Weight {
get {
if ((curObj["Weight"] == null)) {
return System.Convert.ToUInt32(0);
}
return ((uint)(curObj["Weight"]));
}
}
private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) {
if (((path != null)
&& (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) {
return true;
}
else {
return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam));
}
}
private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) {
if (((theObj != null)
&& (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) {
return true;
}
else {
System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"]));
if ((parentClasses != null)) {
int count = 0;
for (count = 0; (count < parentClasses.Length); count = (count + 1)) {
if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) {
return true;
}
}
}
}
return false;
}
private bool ShouldSerializeAutomaticAllocation() {
if ((this.IsAutomaticAllocationNull == false)) {
return true;
}
return false;
}
private bool ShouldSerializeAutomaticDeallocation() {
if ((this.IsAutomaticDeallocationNull == false)) {
return true;
}
return false;
}
private bool ShouldSerializeConsumerVisibility() {
if ((this.IsConsumerVisibilityNull == false)) {
return true;
}
return false;
}
private bool ShouldSerializeLimit() {
if ((this.IsLimitNull == false)) {
return true;
}
return false;
}
private bool ShouldSerializeMappingBehavior() {
if ((this.IsMappingBehaviorNull == false)) {
return true;
}
return false;
}
private bool ShouldSerializeReservation() {
if ((this.IsReservationNull == false)) {
return true;
}
return false;
}
private bool ShouldSerializeResourceType() {
if ((this.IsResourceTypeNull == false)) {
return true;
}
return false;
}
private bool ShouldSerializeVirtualQuantity() {
if ((this.IsVirtualQuantityNull == false)) {
return true;
}
return false;
}
private bool ShouldSerializeWeight() {
if ((this.IsWeightNull == false)) {
return true;
}
return false;
}
[Browsable(true)]
public void CommitObject() {
if ((isEmbedded == false)) {
PrivateLateBoundObject.Put();
}
}
[Browsable(true)]
public void CommitObject(System.Management.PutOptions putOptions) {
if ((isEmbedded == false)) {
PrivateLateBoundObject.Put(putOptions);
}
}
private void Initialize() {
AutoCommitProp = true;
isEmbedded = false;
}
private static string ConstructPath(string keyInstanceID) {
string strPath = "ROOT\\virtualization:Msvm_ResourceAllocationSettingData";
strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\""))));
return strPath;
}
private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) {
Initialize();
if ((path != null)) {
if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) {
throw new System.ArgumentException("Class name does not match.");
}
}
PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions);
PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject);
curObj = PrivateLateBoundObject;
}
// Different overloads of GetInstances() help in enumerating instances of the WMI class.
public static ResourceAllocationSettingDataCollection GetInstances() {
return GetInstances(null, null, null);
}
public static ResourceAllocationSettingDataCollection GetInstances(string condition) {
return GetInstances(null, condition, null);
}
public static ResourceAllocationSettingDataCollection GetInstances(string[] selectedProperties) {
return GetInstances(null, null, selectedProperties);
}
public static ResourceAllocationSettingDataCollection GetInstances(string condition, string[] selectedProperties) {
return GetInstances(null, condition, selectedProperties);
}
public static ResourceAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) {
if ((mgmtScope == null)) {
if ((statMgmtScope == null)) {
mgmtScope = new System.Management.ManagementScope();
mgmtScope.Path.NamespacePath = "root\\virtualization";
}
else {
mgmtScope = statMgmtScope;
}
}
System.Management.ManagementPath pathObj = new System.Management.ManagementPath();
pathObj.ClassName = "Msvm_ResourceAllocationSettingData";
pathObj.NamespacePath = "root\\virtualization";
System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null);
if ((enumOptions == null)) {
enumOptions = new System.Management.EnumerationOptions();
enumOptions.EnsureLocatable = true;
}
return new ResourceAllocationSettingDataCollection(clsObject.GetInstances(enumOptions));
}
public static ResourceAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) {
return GetInstances(mgmtScope, condition, null);
}
public static ResourceAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) {
return GetInstances(mgmtScope, null, selectedProperties);
}
public static ResourceAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) {
if ((mgmtScope == null)) {
if ((statMgmtScope == null)) {
mgmtScope = new System.Management.ManagementScope();
mgmtScope.Path.NamespacePath = "root\\virtualization";
}
else {
mgmtScope = statMgmtScope;
}
}
System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_ResourceAllocationSettingData", condition, selectedProperties));
System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions();
enumOptions.EnsureLocatable = true;
ObjectSearcher.Options = enumOptions;
return new ResourceAllocationSettingDataCollection(ObjectSearcher.Get());
}
[Browsable(true)]
public static ResourceAllocationSettingData CreateInstance() {
System.Management.ManagementScope mgmtScope = null;
if ((statMgmtScope == null)) {
mgmtScope = new System.Management.ManagementScope();
mgmtScope.Path.NamespacePath = CreatedWmiNamespace;
}
else {
mgmtScope = statMgmtScope;
}
System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName);
System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null);
return new ResourceAllocationSettingData(tmpMgmtClass.CreateInstance());
}
[Browsable(true)]
public void Delete() {
PrivateLateBoundObject.Delete();
}
// Enumerator implementation for enumerating instances of the class.
public class ResourceAllocationSettingDataCollection : object, ICollection {
private ManagementObjectCollection privColObj;
public ResourceAllocationSettingDataCollection(ManagementObjectCollection objCollection) {
privColObj = objCollection;
}
public virtual int Count {
get {
return privColObj.Count;
}
}
public virtual bool IsSynchronized {
get {
return privColObj.IsSynchronized;
}
}
public virtual object SyncRoot {
get {
return this;
}
}
public virtual void CopyTo(System.Array array, int index) {
privColObj.CopyTo(array, index);
int nCtr;
for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) {
array.SetValue(new ResourceAllocationSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr);
}
}
public virtual System.Collections.IEnumerator GetEnumerator() {
return new ResourceAllocationSettingDataEnumerator(privColObj.GetEnumerator());
}
public class ResourceAllocationSettingDataEnumerator : object, System.Collections.IEnumerator {
private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum;
public ResourceAllocationSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) {
privObjEnum = objEnum;
}
public virtual object Current {
get {
return new ResourceAllocationSettingData(((System.Management.ManagementObject)(privObjEnum.Current)));
}
}
public virtual bool MoveNext() {
return privObjEnum.MoveNext();
}
public virtual void Reset() {
privObjEnum.Reset();
}
}
}
// TypeConverter to handle null values for ValueType properties
public class WMIValueTypeConverter : TypeConverter {
private TypeConverter baseConverter;
private System.Type baseType;
public WMIValueTypeConverter(System.Type inBaseType) {
baseConverter = TypeDescriptor.GetConverter(inBaseType);
baseType = inBaseType;
}
public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) {
return baseConverter.CanConvertFrom(context, srcType);
}
public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) {
return baseConverter.CanConvertTo(context, destinationType);
}
public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) {
return baseConverter.ConvertFrom(context, culture, value);
}
public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) {
return baseConverter.CreateInstance(context, dictionary);
}
public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) {
return baseConverter.GetCreateInstanceSupported(context);
}
public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) {
return baseConverter.GetProperties(context, value, attributeVar);
}
public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) {
return baseConverter.GetPropertiesSupported(context);
}
public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) {
return baseConverter.GetStandardValues(context);
}
public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) {
return baseConverter.GetStandardValuesExclusive(context);
}
public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) {
return baseConverter.GetStandardValuesSupported(context);
}
public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) {
if ((baseType.BaseType == typeof(System.Enum))) {
if ((value.GetType() == destinationType)) {
return value;
}
if ((((value == null)
&& (context != null))
&& (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) {
return "NULL_ENUM_VALUE" ;
}
return baseConverter.ConvertTo(context, culture, value, destinationType);
}
if (((baseType == typeof(bool))
&& (baseType.BaseType == typeof(System.ValueType)))) {
if ((((value == null)
&& (context != null))
&& (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) {
return "";
}
return baseConverter.ConvertTo(context, culture, value, destinationType);
}
if (((context != null)
&& (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) {
return "";
}
return baseConverter.ConvertTo(context, culture, value, destinationType);
}
}
// Embedded class to represent WMI system Properties.
[TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))]
public class ManagementSystemProperties {
private System.Management.ManagementBaseObject PrivateLateBoundObject;
public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) {
PrivateLateBoundObject = ManagedObject;
}
[Browsable(true)]
public int GENUS {
get {
return ((int)(PrivateLateBoundObject["__GENUS"]));
}
}
[Browsable(true)]
public string CLASS {
get {
return ((string)(PrivateLateBoundObject["__CLASS"]));
}
}
[Browsable(true)]
public string SUPERCLASS {
get {
return ((string)(PrivateLateBoundObject["__SUPERCLASS"]));
}
}
[Browsable(true)]
public string DYNASTY {
get {
return ((string)(PrivateLateBoundObject["__DYNASTY"]));
}
}
[Browsable(true)]
public string RELPATH {
get {
return ((string)(PrivateLateBoundObject["__RELPATH"]));
}
}
[Browsable(true)]
public int PROPERTY_COUNT {
get {
return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"]));
}
}
[Browsable(true)]
public string[] DERIVATION {
get {
return ((string[])(PrivateLateBoundObject["__DERIVATION"]));
}
}
[Browsable(true)]
public string SERVER {
get {
return ((string)(PrivateLateBoundObject["__SERVER"]));
}
}
[Browsable(true)]
public string NAMESPACE {
get {
return ((string)(PrivateLateBoundObject["__NAMESPACE"]));
}
}
[Browsable(true)]
public string PATH {
get {
return ((string)(PrivateLateBoundObject["__PATH"]));
}
}
}
}
}

View File

@ -0,0 +1,885 @@
namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION {
using System;
using System.ComponentModel;
using System.Management;
using System.Collections;
using System.Globalization;
using System.ComponentModel.Design.Serialization;
using System.Reflection;
// Functions ShouldSerialize<PropertyName> are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use Is<PropertyName>Null function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio.
// Functions Is<PropertyName>Null() are used to check if a property is NULL.
// Functions Reset<PropertyName> are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL.
// Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used.
// An Early Bound class generated for the WMI class.Msvm_VLANEndpointSettingData
public class VLANEndpointSettingData : System.ComponentModel.Component {
// Private property to hold the WMI namespace in which the class resides.
private static string CreatedWmiNamespace = "ROOT\\virtualization";
// Private property to hold the name of WMI class which created this class.
public static string CreatedClassName = "Msvm_VLANEndpointSettingData";
// Private member variable to hold the ManagementScope which is used by the various methods.
private static System.Management.ManagementScope statMgmtScope = null;
private ManagementSystemProperties PrivateSystemProperties;
// Underlying lateBound WMI object.
private System.Management.ManagementObject PrivateLateBoundObject;
// Member variable to store the 'automatic commit' behavior for the class.
private bool AutoCommitProp;
// Private variable to hold the embedded property representing the instance.
private System.Management.ManagementBaseObject embeddedObj;
// The current WMI object used
private System.Management.ManagementBaseObject curObj;
// Flag to indicate if the instance is an embedded object.
private bool isEmbedded;
// Below are different overloads of constructors to initialize an instance of the class with a WMI object.
public VLANEndpointSettingData() {
this.InitializeObject(null, null, null);
}
public VLANEndpointSettingData(string keyInstanceID) {
this.InitializeObject(null, new System.Management.ManagementPath(VLANEndpointSettingData.ConstructPath(keyInstanceID)), null);
}
public VLANEndpointSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) {
this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(VLANEndpointSettingData.ConstructPath(keyInstanceID)), null);
}
public VLANEndpointSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) {
this.InitializeObject(null, path, getOptions);
}
public VLANEndpointSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) {
this.InitializeObject(mgmtScope, path, null);
}
public VLANEndpointSettingData(System.Management.ManagementPath path) {
this.InitializeObject(null, path, null);
}
public VLANEndpointSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) {
this.InitializeObject(mgmtScope, path, getOptions);
}
public VLANEndpointSettingData(System.Management.ManagementObject theObject) {
Initialize();
if ((CheckIfProperClass(theObject) == true)) {
PrivateLateBoundObject = theObject;
PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject);
curObj = PrivateLateBoundObject;
}
else {
throw new System.ArgumentException("Class name does not match.");
}
}
public VLANEndpointSettingData(System.Management.ManagementBaseObject theObject) {
Initialize();
if ((CheckIfProperClass(theObject) == true)) {
embeddedObj = theObject;
PrivateSystemProperties = new ManagementSystemProperties(theObject);
curObj = embeddedObj;
isEmbedded = true;
}
else {
throw new System.ArgumentException("Class name does not match.");
}
}
// Property returns the namespace of the WMI class.
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string OriginatingNamespace {
get {
return "ROOT\\virtualization";
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string ManagementClassName {
get {
string strRet = CreatedClassName;
if ((curObj != null)) {
if ((curObj.ClassPath != null)) {
strRet = ((string)(curObj["__CLASS"]));
if (((strRet == null)
|| (strRet == string.Empty))) {
strRet = CreatedClassName;
}
}
}
return strRet;
}
}
// Property pointing to an embedded object to get System properties of the WMI object.
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public ManagementSystemProperties SystemProperties {
get {
return PrivateSystemProperties;
}
}
// Property returning the underlying lateBound object.
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public System.Management.ManagementBaseObject LateBoundObject {
get {
return curObj;
}
}
// ManagementScope of the object.
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public System.Management.ManagementScope Scope {
get {
if ((isEmbedded == false)) {
return PrivateLateBoundObject.Scope;
}
else {
return null;
}
}
set {
if ((isEmbedded == false)) {
PrivateLateBoundObject.Scope = value;
}
}
}
// Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property).
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool AutoCommit {
get {
return AutoCommitProp;
}
set {
AutoCommitProp = value;
}
}
// The ManagementPath of the underlying WMI object.
[Browsable(true)]
public System.Management.ManagementPath Path {
get {
if ((isEmbedded == false)) {
return PrivateLateBoundObject.Path;
}
else {
return null;
}
}
set {
if ((isEmbedded == false)) {
if ((CheckIfProperClass(null, value, null) != true)) {
throw new System.ArgumentException("Class name does not match.");
}
PrivateLateBoundObject.Path = value;
}
}
}
// Public static scope property which is used by the various methods.
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public static System.Management.ManagementScope StaticScope {
get {
return statMgmtScope;
}
set {
statMgmtScope = value;
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsAccessVLANNull {
get {
if ((curObj["AccessVLAN"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[TypeConverter(typeof(WMIValueTypeConverter))]
public ushort AccessVLAN {
get {
if ((curObj["AccessVLAN"] == null)) {
return System.Convert.ToUInt16(0);
}
return ((ushort)(curObj["AccessVLAN"]));
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string Caption {
get {
return ((string)(curObj["Caption"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsDefaultVLANNull {
get {
if ((curObj["DefaultVLAN"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[TypeConverter(typeof(WMIValueTypeConverter))]
public ushort DefaultVLAN {
get {
if ((curObj["DefaultVLAN"] == null)) {
return System.Convert.ToUInt16(0);
}
return ((ushort)(curObj["DefaultVLAN"]));
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string Description {
get {
return ((string)(curObj["Description"]));
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string ElementName {
get {
return ((string)(curObj["ElementName"]));
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string InstanceID {
get {
return ((string)(curObj["InstanceID"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsNativeVLANNull {
get {
if ((curObj["NativeVLAN"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[TypeConverter(typeof(WMIValueTypeConverter))]
public ushort NativeVLAN {
get {
if ((curObj["NativeVLAN"] == null)) {
return System.Convert.ToUInt16(0);
}
return ((ushort)(curObj["NativeVLAN"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsPrimaryVlanNull {
get {
if ((curObj["PrimaryVlan"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description("The primary Vlan if the port is in Private Vlan mode.")]
[TypeConverter(typeof(WMIValueTypeConverter))]
public ushort PrimaryVlan {
get {
if ((curObj["PrimaryVlan"] == null)) {
return System.Convert.ToUInt16(0);
}
return ((ushort)(curObj["PrimaryVlan"]));
}
set {
curObj["PrimaryVlan"] = value;
if (((isEmbedded == false)
&& (AutoCommitProp == true))) {
PrivateLateBoundObject.Put();
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public ushort[] PruneEligibleVLANList {
get {
return ((ushort[])(curObj["PruneEligibleVLANList"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsPVlanModeNull {
get {
if ((curObj["PVlanMode"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description("The private VLAN Mode mode supported by this port.")]
[TypeConverter(typeof(WMIValueTypeConverter))]
public PVlanModeValues PVlanMode {
get {
if ((curObj["PVlanMode"] == null)) {
return ((PVlanModeValues)(System.Convert.ToInt32(3)));
}
return ((PVlanModeValues)(System.Convert.ToInt32(curObj["PVlanMode"])));
}
set {
if ((PVlanModeValues.NULL_ENUM_VALUE == value)) {
curObj["PVlanMode"] = null;
}
else {
curObj["PVlanMode"] = value;
}
if (((isEmbedded == false)
&& (AutoCommitProp == true))) {
PrivateLateBoundObject.Put();
}
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsSecondaryVlanNull {
get {
if ((curObj["SecondaryVlan"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description("The secondary Vlan if the port is in Private Vlan mode.")]
[TypeConverter(typeof(WMIValueTypeConverter))]
public ushort SecondaryVlan {
get {
if ((curObj["SecondaryVlan"] == null)) {
return System.Convert.ToUInt16(0);
}
return ((ushort)(curObj["SecondaryVlan"]));
}
set {
curObj["SecondaryVlan"] = value;
if (((isEmbedded == false)
&& (AutoCommitProp == true))) {
PrivateLateBoundObject.Put();
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public ushort[] TrunkedVLANList {
get {
return ((ushort[])(curObj["TrunkedVLANList"]));
}
}
private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) {
if (((path != null)
&& (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) {
return true;
}
else {
return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam));
}
}
private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) {
if (((theObj != null)
&& (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) {
return true;
}
else {
System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"]));
if ((parentClasses != null)) {
int count = 0;
for (count = 0; (count < parentClasses.Length); count = (count + 1)) {
if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) {
return true;
}
}
}
}
return false;
}
private bool ShouldSerializeAccessVLAN() {
if ((this.IsAccessVLANNull == false)) {
return true;
}
return false;
}
private bool ShouldSerializeDefaultVLAN() {
if ((this.IsDefaultVLANNull == false)) {
return true;
}
return false;
}
private bool ShouldSerializeNativeVLAN() {
if ((this.IsNativeVLANNull == false)) {
return true;
}
return false;
}
private bool ShouldSerializePrimaryVlan() {
if ((this.IsPrimaryVlanNull == false)) {
return true;
}
return false;
}
private void ResetPrimaryVlan() {
curObj["PrimaryVlan"] = null;
if (((isEmbedded == false)
&& (AutoCommitProp == true))) {
PrivateLateBoundObject.Put();
}
}
private bool ShouldSerializePVlanMode() {
if ((this.IsPVlanModeNull == false)) {
return true;
}
return false;
}
private void ResetPVlanMode() {
curObj["PVlanMode"] = null;
if (((isEmbedded == false)
&& (AutoCommitProp == true))) {
PrivateLateBoundObject.Put();
}
}
private bool ShouldSerializeSecondaryVlan() {
if ((this.IsSecondaryVlanNull == false)) {
return true;
}
return false;
}
private void ResetSecondaryVlan() {
curObj["SecondaryVlan"] = null;
if (((isEmbedded == false)
&& (AutoCommitProp == true))) {
PrivateLateBoundObject.Put();
}
}
[Browsable(true)]
public void CommitObject() {
if ((isEmbedded == false)) {
PrivateLateBoundObject.Put();
}
}
[Browsable(true)]
public void CommitObject(System.Management.PutOptions putOptions) {
if ((isEmbedded == false)) {
PrivateLateBoundObject.Put(putOptions);
}
}
private void Initialize() {
AutoCommitProp = true;
isEmbedded = false;
}
private static string ConstructPath(string keyInstanceID) {
string strPath = "ROOT\\virtualization:Msvm_VLANEndpointSettingData";
strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\""))));
return strPath;
}
private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) {
Initialize();
if ((path != null)) {
if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) {
throw new System.ArgumentException("Class name does not match.");
}
}
PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions);
PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject);
curObj = PrivateLateBoundObject;
}
// Different overloads of GetInstances() help in enumerating instances of the WMI class.
public static VLANEndpointSettingDataCollection GetInstances() {
return GetInstances(null, null, null);
}
public static VLANEndpointSettingDataCollection GetInstances(string condition) {
return GetInstances(null, condition, null);
}
public static VLANEndpointSettingDataCollection GetInstances(string[] selectedProperties) {
return GetInstances(null, null, selectedProperties);
}
public static VLANEndpointSettingDataCollection GetInstances(string condition, string[] selectedProperties) {
return GetInstances(null, condition, selectedProperties);
}
public static VLANEndpointSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) {
if ((mgmtScope == null)) {
if ((statMgmtScope == null)) {
mgmtScope = new System.Management.ManagementScope();
mgmtScope.Path.NamespacePath = "root\\virtualization";
}
else {
mgmtScope = statMgmtScope;
}
}
System.Management.ManagementPath pathObj = new System.Management.ManagementPath();
pathObj.ClassName = "Msvm_VLANEndpointSettingData";
pathObj.NamespacePath = "root\\virtualization";
System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null);
if ((enumOptions == null)) {
enumOptions = new System.Management.EnumerationOptions();
enumOptions.EnsureLocatable = true;
}
return new VLANEndpointSettingDataCollection(clsObject.GetInstances(enumOptions));
}
public static VLANEndpointSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) {
return GetInstances(mgmtScope, condition, null);
}
public static VLANEndpointSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) {
return GetInstances(mgmtScope, null, selectedProperties);
}
public static VLANEndpointSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) {
if ((mgmtScope == null)) {
if ((statMgmtScope == null)) {
mgmtScope = new System.Management.ManagementScope();
mgmtScope.Path.NamespacePath = "root\\virtualization";
}
else {
mgmtScope = statMgmtScope;
}
}
System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_VLANEndpointSettingData", condition, selectedProperties));
System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions();
enumOptions.EnsureLocatable = true;
ObjectSearcher.Options = enumOptions;
return new VLANEndpointSettingDataCollection(ObjectSearcher.Get());
}
[Browsable(true)]
public static VLANEndpointSettingData CreateInstance() {
System.Management.ManagementScope mgmtScope = null;
if ((statMgmtScope == null)) {
mgmtScope = new System.Management.ManagementScope();
mgmtScope.Path.NamespacePath = CreatedWmiNamespace;
}
else {
mgmtScope = statMgmtScope;
}
System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName);
System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null);
return new VLANEndpointSettingData(tmpMgmtClass.CreateInstance());
}
[Browsable(true)]
public void Delete() {
PrivateLateBoundObject.Delete();
}
public enum PVlanModeValues {
Unknown0 = 0,
Incoming = 1,
Outgoing = 2,
NULL_ENUM_VALUE = 3,
}
// Enumerator implementation for enumerating instances of the class.
public class VLANEndpointSettingDataCollection : object, ICollection {
private ManagementObjectCollection privColObj;
public VLANEndpointSettingDataCollection(ManagementObjectCollection objCollection) {
privColObj = objCollection;
}
public virtual int Count {
get {
return privColObj.Count;
}
}
public virtual bool IsSynchronized {
get {
return privColObj.IsSynchronized;
}
}
public virtual object SyncRoot {
get {
return this;
}
}
public virtual void CopyTo(System.Array array, int index) {
privColObj.CopyTo(array, index);
int nCtr;
for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) {
array.SetValue(new VLANEndpointSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr);
}
}
public virtual System.Collections.IEnumerator GetEnumerator() {
return new VLANEndpointSettingDataEnumerator(privColObj.GetEnumerator());
}
public class VLANEndpointSettingDataEnumerator : object, System.Collections.IEnumerator {
private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum;
public VLANEndpointSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) {
privObjEnum = objEnum;
}
public virtual object Current {
get {
return new VLANEndpointSettingData(((System.Management.ManagementObject)(privObjEnum.Current)));
}
}
public virtual bool MoveNext() {
return privObjEnum.MoveNext();
}
public virtual void Reset() {
privObjEnum.Reset();
}
}
}
// TypeConverter to handle null values for ValueType properties
public class WMIValueTypeConverter : TypeConverter {
private TypeConverter baseConverter;
private System.Type baseType;
public WMIValueTypeConverter(System.Type inBaseType) {
baseConverter = TypeDescriptor.GetConverter(inBaseType);
baseType = inBaseType;
}
public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) {
return baseConverter.CanConvertFrom(context, srcType);
}
public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) {
return baseConverter.CanConvertTo(context, destinationType);
}
public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) {
return baseConverter.ConvertFrom(context, culture, value);
}
public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) {
return baseConverter.CreateInstance(context, dictionary);
}
public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) {
return baseConverter.GetCreateInstanceSupported(context);
}
public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) {
return baseConverter.GetProperties(context, value, attributeVar);
}
public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) {
return baseConverter.GetPropertiesSupported(context);
}
public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) {
return baseConverter.GetStandardValues(context);
}
public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) {
return baseConverter.GetStandardValuesExclusive(context);
}
public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) {
return baseConverter.GetStandardValuesSupported(context);
}
public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) {
if ((baseType.BaseType == typeof(System.Enum))) {
if ((value.GetType() == destinationType)) {
return value;
}
if ((((value == null)
&& (context != null))
&& (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) {
return "NULL_ENUM_VALUE" ;
}
return baseConverter.ConvertTo(context, culture, value, destinationType);
}
if (((baseType == typeof(bool))
&& (baseType.BaseType == typeof(System.ValueType)))) {
if ((((value == null)
&& (context != null))
&& (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) {
return "";
}
return baseConverter.ConvertTo(context, culture, value, destinationType);
}
if (((context != null)
&& (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) {
return "";
}
return baseConverter.ConvertTo(context, culture, value, destinationType);
}
}
// Embedded class to represent WMI system Properties.
[TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))]
public class ManagementSystemProperties {
private System.Management.ManagementBaseObject PrivateLateBoundObject;
public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) {
PrivateLateBoundObject = ManagedObject;
}
[Browsable(true)]
public int GENUS {
get {
return ((int)(PrivateLateBoundObject["__GENUS"]));
}
}
[Browsable(true)]
public string CLASS {
get {
return ((string)(PrivateLateBoundObject["__CLASS"]));
}
}
[Browsable(true)]
public string SUPERCLASS {
get {
return ((string)(PrivateLateBoundObject["__SUPERCLASS"]));
}
}
[Browsable(true)]
public string DYNASTY {
get {
return ((string)(PrivateLateBoundObject["__DYNASTY"]));
}
}
[Browsable(true)]
public string RELPATH {
get {
return ((string)(PrivateLateBoundObject["__RELPATH"]));
}
}
[Browsable(true)]
public int PROPERTY_COUNT {
get {
return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"]));
}
}
[Browsable(true)]
public string[] DERIVATION {
get {
return ((string[])(PrivateLateBoundObject["__DERIVATION"]));
}
}
[Browsable(true)]
public string SERVER {
get {
return ((string)(PrivateLateBoundObject["__SERVER"]));
}
}
[Browsable(true)]
public string NAMESPACE {
get {
return ((string)(PrivateLateBoundObject["__NAMESPACE"]));
}
}
[Browsable(true)]
public string PATH {
get {
return ((string)(PrivateLateBoundObject["__PATH"]));
}
}
}
}
}

View File

@ -0,0 +1,731 @@
namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION {
using System;
using System.ComponentModel;
using System.Management;
using System.Collections;
using System.Globalization;
using System.ComponentModel.Design.Serialization;
using System.Reflection;
// Functions ShouldSerialize<PropertyName> are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use Is<PropertyName>Null function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio.
// Functions Is<PropertyName>Null() are used to check if a property is NULL.
// Functions Reset<PropertyName> are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL.
// Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used.
// An Early Bound class generated for the WMI class.Msvm_VirtualSystemManagementServiceSettingData
public class VirtualSystemManagementServiceSettingData : System.ComponentModel.Component {
// Private property to hold the WMI namespace in which the class resides.
private static string CreatedWmiNamespace = "ROOT\\virtualization";
// Private property to hold the name of WMI class which created this class.
private static string CreatedClassName = "Msvm_VirtualSystemManagementServiceSettingData";
// Private member variable to hold the ManagementScope which is used by the various methods.
private static System.Management.ManagementScope statMgmtScope = null;
private ManagementSystemProperties PrivateSystemProperties;
// Underlying lateBound WMI object.
private System.Management.ManagementObject PrivateLateBoundObject;
// Member variable to store the 'automatic commit' behavior for the class.
private bool AutoCommitProp;
// Private variable to hold the embedded property representing the instance.
private System.Management.ManagementBaseObject embeddedObj;
// The current WMI object used
private System.Management.ManagementBaseObject curObj;
// Flag to indicate if the instance is an embedded object.
private bool isEmbedded;
// Below are different overloads of constructors to initialize an instance of the class with a WMI object.
public VirtualSystemManagementServiceSettingData() {
this.InitializeObject(null, null, null);
}
public VirtualSystemManagementServiceSettingData(string keyInstanceID) {
this.InitializeObject(null, new System.Management.ManagementPath(VirtualSystemManagementServiceSettingData.ConstructPath(keyInstanceID)), null);
}
public VirtualSystemManagementServiceSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) {
this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(VirtualSystemManagementServiceSettingData.ConstructPath(keyInstanceID)), null);
}
public VirtualSystemManagementServiceSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) {
this.InitializeObject(null, path, getOptions);
}
public VirtualSystemManagementServiceSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) {
this.InitializeObject(mgmtScope, path, null);
}
public VirtualSystemManagementServiceSettingData(System.Management.ManagementPath path) {
this.InitializeObject(null, path, null);
}
public VirtualSystemManagementServiceSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) {
this.InitializeObject(mgmtScope, path, getOptions);
}
public VirtualSystemManagementServiceSettingData(System.Management.ManagementObject theObject) {
Initialize();
if ((CheckIfProperClass(theObject) == true)) {
PrivateLateBoundObject = theObject;
PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject);
curObj = PrivateLateBoundObject;
}
else {
throw new System.ArgumentException("Class name does not match.");
}
}
public VirtualSystemManagementServiceSettingData(System.Management.ManagementBaseObject theObject) {
Initialize();
if ((CheckIfProperClass(theObject) == true)) {
embeddedObj = theObject;
PrivateSystemProperties = new ManagementSystemProperties(theObject);
curObj = embeddedObj;
isEmbedded = true;
}
else {
throw new System.ArgumentException("Class name does not match.");
}
}
// Property returns the namespace of the WMI class.
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string OriginatingNamespace {
get {
return "ROOT\\virtualization";
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string ManagementClassName {
get {
string strRet = CreatedClassName;
if ((curObj != null)) {
if ((curObj.ClassPath != null)) {
strRet = ((string)(curObj["__CLASS"]));
if (((strRet == null)
|| (strRet == string.Empty))) {
strRet = CreatedClassName;
}
}
}
return strRet;
}
}
// Property pointing to an embedded object to get System properties of the WMI object.
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public ManagementSystemProperties SystemProperties {
get {
return PrivateSystemProperties;
}
}
// Property returning the underlying lateBound object.
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public System.Management.ManagementBaseObject LateBoundObject {
get {
return curObj;
}
}
// ManagementScope of the object.
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public System.Management.ManagementScope Scope {
get {
if ((isEmbedded == false)) {
return PrivateLateBoundObject.Scope;
}
else {
return null;
}
}
set {
if ((isEmbedded == false)) {
PrivateLateBoundObject.Scope = value;
}
}
}
// Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property).
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool AutoCommit {
get {
return AutoCommitProp;
}
set {
AutoCommitProp = value;
}
}
// The ManagementPath of the underlying WMI object.
[Browsable(true)]
public System.Management.ManagementPath Path {
get {
if ((isEmbedded == false)) {
return PrivateLateBoundObject.Path;
}
else {
return null;
}
}
set {
if ((isEmbedded == false)) {
if ((CheckIfProperClass(null, value, null) != true)) {
throw new System.ArgumentException("Class name does not match.");
}
PrivateLateBoundObject.Path = value;
}
}
}
// Public static scope property which is used by the various methods.
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public static System.Management.ManagementScope StaticScope {
get {
return statMgmtScope;
}
set {
statMgmtScope = value;
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description(@"Used by OEMs to allow BIOS-locked Windows operating systems to run in the virtual machine. This string must be exactly 32 characters in length.
This is a read-only property, but it can be changed using the ModifyServiceSettings method of the Msvm_VirtualSystemManagementService class.")]
public string BiosLockString {
get {
return ((string)(curObj["BiosLockString"]));
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string Caption {
get {
return ((string)(curObj["Caption"]));
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description("The default external data root. By default, \"root\\ProgramData\\Microsoft\\Windows\\V" +
"irtualization\".\nThis is a read-only property, but it can be changed using the Mo" +
"difyServiceSettings method of the Msvm_VirtualSystemManagementService class.")]
public string DefaultExternalDataRoot {
get {
return ((string)(curObj["DefaultExternalDataRoot"]));
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description("The default virtual hard disk path. By default, \"root\\Users\\Public\\Documents\\Virt" +
"ual Hard Disks\".\nThis is a read-only property, but it can be changed using the M" +
"odifyServiceSettings method of the Msvm_VirtualSystemManagementService class.")]
public string DefaultVirtualHardDiskPath {
get {
return ((string)(curObj["DefaultVirtualHardDiskPath"]));
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string Description {
get {
return ((string)(curObj["Description"]));
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string ElementName {
get {
return ((string)(curObj["ElementName"]));
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string InstanceID {
get {
return ((string)(curObj["InstanceID"]));
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description("The maximum MAC address for dynamically generated MAC addresses.\nThis is a read-o" +
"nly property, but it can be changed using the ModifyServiceSettings method of th" +
"e Msvm_VirtualSystemManagementService class.")]
public string MaximumMacAddress {
get {
return ((string)(curObj["MaximumMacAddress"]));
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description("The minimum MAC address for dynamically generated MAC addresses.\nThis is a read-o" +
"nly property, but it can be changed using the ModifyServiceSettings method of th" +
"e Msvm_VirtualSystemManagementService class.")]
public string MinimumMacAddress {
get {
return ((string)(curObj["MinimumMacAddress"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsNumaSpanningEnabledNull {
get {
if ((curObj["NumaSpanningEnabled"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description("Reserved for future use.")]
[TypeConverter(typeof(WMIValueTypeConverter))]
public bool NumaSpanningEnabled {
get {
if ((curObj["NumaSpanningEnabled"] == null)) {
return System.Convert.ToBoolean(0);
}
return ((bool)(curObj["NumaSpanningEnabled"]));
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description("Controls memory allocation for the VMs on non-uniform memory access (NUMA) system" +
"s.\nThis is a read-only property, but it can be changed using the ModifyServiceSe" +
"ttings method of the Msvm_VirtualSystemManagementService class.")]
public string PrimaryOwnerContact {
get {
return ((string)(curObj["PrimaryOwnerContact"]));
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description(@"Describes how the primary system owner can be reached (for example, phone number or e-mail address). By default, empty. This name may not exceed 256 characters in length.
This is a read-only property, but it can be changed using the ModifyServiceSettings method of the Msvm_VirtualSystemManagementService class.")]
public string PrimaryOwnerName {
get {
return ((string)(curObj["PrimaryOwnerName"]));
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description("This is a read-only property, but it can be changed using the ModifyServiceSettin" +
"gs method of the Msvm_VirtualSystemManagementService class.")]
public string ScopeOfResidence {
get {
return ((string)(curObj["ScopeOfResidence"]));
}
}
private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) {
if (((path != null)
&& (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) {
return true;
}
else {
return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam));
}
}
private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) {
if (((theObj != null)
&& (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) {
return true;
}
else {
System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"]));
if ((parentClasses != null)) {
int count = 0;
for (count = 0; (count < parentClasses.Length); count = (count + 1)) {
if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) {
return true;
}
}
}
}
return false;
}
private bool ShouldSerializeNumaSpanningEnabled() {
if ((this.IsNumaSpanningEnabledNull == false)) {
return true;
}
return false;
}
[Browsable(true)]
public void CommitObject() {
if ((isEmbedded == false)) {
PrivateLateBoundObject.Put();
}
}
[Browsable(true)]
public void CommitObject(System.Management.PutOptions putOptions) {
if ((isEmbedded == false)) {
PrivateLateBoundObject.Put(putOptions);
}
}
private void Initialize() {
AutoCommitProp = true;
isEmbedded = false;
}
private static string ConstructPath(string keyInstanceID) {
string strPath = "ROOT\\virtualization:Msvm_VirtualSystemManagementServiceSettingData";
strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\""))));
return strPath;
}
private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) {
Initialize();
if ((path != null)) {
if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) {
throw new System.ArgumentException("Class name does not match.");
}
}
PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions);
PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject);
curObj = PrivateLateBoundObject;
}
// Different overloads of GetInstances() help in enumerating instances of the WMI class.
public static VirtualSystemManagementServiceSettingDataCollection GetInstances() {
return GetInstances(null, null, null);
}
public static VirtualSystemManagementServiceSettingDataCollection GetInstances(string condition) {
return GetInstances(null, condition, null);
}
public static VirtualSystemManagementServiceSettingDataCollection GetInstances(string[] selectedProperties) {
return GetInstances(null, null, selectedProperties);
}
public static VirtualSystemManagementServiceSettingDataCollection GetInstances(string condition, string[] selectedProperties) {
return GetInstances(null, condition, selectedProperties);
}
public static VirtualSystemManagementServiceSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) {
if ((mgmtScope == null)) {
if ((statMgmtScope == null)) {
mgmtScope = new System.Management.ManagementScope();
mgmtScope.Path.NamespacePath = "root\\virtualization";
}
else {
mgmtScope = statMgmtScope;
}
}
System.Management.ManagementPath pathObj = new System.Management.ManagementPath();
pathObj.ClassName = "Msvm_VirtualSystemManagementServiceSettingData";
pathObj.NamespacePath = "root\\virtualization";
System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null);
if ((enumOptions == null)) {
enumOptions = new System.Management.EnumerationOptions();
enumOptions.EnsureLocatable = true;
}
return new VirtualSystemManagementServiceSettingDataCollection(clsObject.GetInstances(enumOptions));
}
public static VirtualSystemManagementServiceSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) {
return GetInstances(mgmtScope, condition, null);
}
public static VirtualSystemManagementServiceSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) {
return GetInstances(mgmtScope, null, selectedProperties);
}
public static VirtualSystemManagementServiceSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) {
if ((mgmtScope == null)) {
if ((statMgmtScope == null)) {
mgmtScope = new System.Management.ManagementScope();
mgmtScope.Path.NamespacePath = "root\\virtualization";
}
else {
mgmtScope = statMgmtScope;
}
}
System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_VirtualSystemManagementServiceSettingData", condition, selectedProperties));
System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions();
enumOptions.EnsureLocatable = true;
ObjectSearcher.Options = enumOptions;
return new VirtualSystemManagementServiceSettingDataCollection(ObjectSearcher.Get());
}
[Browsable(true)]
public static VirtualSystemManagementServiceSettingData CreateInstance() {
System.Management.ManagementScope mgmtScope = null;
if ((statMgmtScope == null)) {
mgmtScope = new System.Management.ManagementScope();
mgmtScope.Path.NamespacePath = CreatedWmiNamespace;
}
else {
mgmtScope = statMgmtScope;
}
System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName);
System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null);
return new VirtualSystemManagementServiceSettingData(tmpMgmtClass.CreateInstance());
}
[Browsable(true)]
public void Delete() {
PrivateLateBoundObject.Delete();
}
// Enumerator implementation for enumerating instances of the class.
public class VirtualSystemManagementServiceSettingDataCollection : object, ICollection {
private ManagementObjectCollection privColObj;
public VirtualSystemManagementServiceSettingDataCollection(ManagementObjectCollection objCollection) {
privColObj = objCollection;
}
public virtual int Count {
get {
return privColObj.Count;
}
}
public virtual bool IsSynchronized {
get {
return privColObj.IsSynchronized;
}
}
public virtual object SyncRoot {
get {
return this;
}
}
public virtual void CopyTo(System.Array array, int index) {
privColObj.CopyTo(array, index);
int nCtr;
for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) {
array.SetValue(new VirtualSystemManagementServiceSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr);
}
}
public virtual System.Collections.IEnumerator GetEnumerator() {
return new VirtualSystemManagementServiceSettingDataEnumerator(privColObj.GetEnumerator());
}
public class VirtualSystemManagementServiceSettingDataEnumerator : object, System.Collections.IEnumerator {
private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum;
public VirtualSystemManagementServiceSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) {
privObjEnum = objEnum;
}
public virtual object Current {
get {
return new VirtualSystemManagementServiceSettingData(((System.Management.ManagementObject)(privObjEnum.Current)));
}
}
public virtual bool MoveNext() {
return privObjEnum.MoveNext();
}
public virtual void Reset() {
privObjEnum.Reset();
}
}
}
// TypeConverter to handle null values for ValueType properties
public class WMIValueTypeConverter : TypeConverter {
private TypeConverter baseConverter;
private System.Type baseType;
public WMIValueTypeConverter(System.Type inBaseType) {
baseConverter = TypeDescriptor.GetConverter(inBaseType);
baseType = inBaseType;
}
public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) {
return baseConverter.CanConvertFrom(context, srcType);
}
public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) {
return baseConverter.CanConvertTo(context, destinationType);
}
public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) {
return baseConverter.ConvertFrom(context, culture, value);
}
public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) {
return baseConverter.CreateInstance(context, dictionary);
}
public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) {
return baseConverter.GetCreateInstanceSupported(context);
}
public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) {
return baseConverter.GetProperties(context, value, attributeVar);
}
public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) {
return baseConverter.GetPropertiesSupported(context);
}
public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) {
return baseConverter.GetStandardValues(context);
}
public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) {
return baseConverter.GetStandardValuesExclusive(context);
}
public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) {
return baseConverter.GetStandardValuesSupported(context);
}
public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) {
if ((baseType.BaseType == typeof(System.Enum))) {
if ((value.GetType() == destinationType)) {
return value;
}
if ((((value == null)
&& (context != null))
&& (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) {
return "NULL_ENUM_VALUE" ;
}
return baseConverter.ConvertTo(context, culture, value, destinationType);
}
if (((baseType == typeof(bool))
&& (baseType.BaseType == typeof(System.ValueType)))) {
if ((((value == null)
&& (context != null))
&& (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) {
return "";
}
return baseConverter.ConvertTo(context, culture, value, destinationType);
}
if (((context != null)
&& (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) {
return "";
}
return baseConverter.ConvertTo(context, culture, value, destinationType);
}
}
// Embedded class to represent WMI system Properties.
[TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))]
public class ManagementSystemProperties {
private System.Management.ManagementBaseObject PrivateLateBoundObject;
public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) {
PrivateLateBoundObject = ManagedObject;
}
[Browsable(true)]
public int GENUS {
get {
return ((int)(PrivateLateBoundObject["__GENUS"]));
}
}
[Browsable(true)]
public string CLASS {
get {
return ((string)(PrivateLateBoundObject["__CLASS"]));
}
}
[Browsable(true)]
public string SUPERCLASS {
get {
return ((string)(PrivateLateBoundObject["__SUPERCLASS"]));
}
}
[Browsable(true)]
public string DYNASTY {
get {
return ((string)(PrivateLateBoundObject["__DYNASTY"]));
}
}
[Browsable(true)]
public string RELPATH {
get {
return ((string)(PrivateLateBoundObject["__RELPATH"]));
}
}
[Browsable(true)]
public int PROPERTY_COUNT {
get {
return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"]));
}
}
[Browsable(true)]
public string[] DERIVATION {
get {
return ((string[])(PrivateLateBoundObject["__DERIVATION"]));
}
}
[Browsable(true)]
public string SERVER {
get {
return ((string)(PrivateLateBoundObject["__SERVER"]));
}
}
[Browsable(true)]
public string NAMESPACE {
get {
return ((string)(PrivateLateBoundObject["__NAMESPACE"]));
}
}
[Browsable(true)]
public string PATH {
get {
return ((string)(PrivateLateBoundObject["__PATH"]));
}
}
}
}
}

View File

@ -0,0 +1,653 @@
namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2
{
using System;
using System.ComponentModel;
using System.Management;
using System.Collections;
using System.Globalization;
using System.ComponentModel.Design.Serialization;
using System.Reflection;
// Functions ShouldSerialize<PropertyName> are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use Is<PropertyName>Null function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio.
// Functions Is<PropertyName>Null() are used to check if a property is NULL.
// Functions Reset<PropertyName> are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL.
// Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used.
// An Early Bound class generated for the WMI class.Msvm_KvpExchangeDataItem
public class KvpExchangeDataItem : System.ComponentModel.Component {
// Private property to hold the WMI namespace in which the class resides.
private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2";
// Private property to hold the name of WMI class which created this class.
private static string CreatedClassName = "Msvm_KvpExchangeDataItem";
// Private member variable to hold the ManagementScope which is used by the various methods.
private static System.Management.ManagementScope statMgmtScope = null;
private ManagementSystemProperties PrivateSystemProperties;
// Underlying lateBound WMI object.
private System.Management.ManagementObject PrivateLateBoundObject;
// Member variable to store the 'automatic commit' behavior for the class.
private bool AutoCommitProp;
// Private variable to hold the embedded property representing the instance.
private System.Management.ManagementBaseObject embeddedObj;
// The current WMI object used
private System.Management.ManagementBaseObject curObj;
// Flag to indicate if the instance is an embedded object.
private bool isEmbedded;
// Below are different overloads of constructors to initialize an instance of the class with a WMI object.
public KvpExchangeDataItem() {
this.InitializeObject(null, null, null);
}
public KvpExchangeDataItem(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) {
this.InitializeObject(null, path, getOptions);
}
public KvpExchangeDataItem(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) {
this.InitializeObject(mgmtScope, path, null);
}
public KvpExchangeDataItem(System.Management.ManagementPath path) {
this.InitializeObject(null, path, null);
}
public KvpExchangeDataItem(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) {
this.InitializeObject(mgmtScope, path, getOptions);
}
public KvpExchangeDataItem(System.Management.ManagementObject theObject) {
Initialize();
if ((CheckIfProperClass(theObject) == true)) {
PrivateLateBoundObject = theObject;
PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject);
curObj = PrivateLateBoundObject;
}
else {
throw new System.ArgumentException("Class name does not match.");
}
}
public KvpExchangeDataItem(System.Management.ManagementBaseObject theObject) {
Initialize();
if ((CheckIfProperClass(theObject) == true)) {
embeddedObj = theObject;
PrivateSystemProperties = new ManagementSystemProperties(theObject);
curObj = embeddedObj;
isEmbedded = true;
}
else {
throw new System.ArgumentException("Class name does not match.");
}
}
// Property returns the namespace of the WMI class.
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string OriginatingNamespace {
get {
return "ROOT\\virtualization\\v2";
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string ManagementClassName {
get {
string strRet = CreatedClassName;
if ((curObj != null)) {
if ((curObj.ClassPath != null)) {
strRet = ((string)(curObj["__CLASS"]));
if (((strRet == null)
|| (strRet == string.Empty))) {
strRet = CreatedClassName;
}
}
}
return strRet;
}
}
// Property pointing to an embedded object to get System properties of the WMI object.
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public ManagementSystemProperties SystemProperties {
get {
return PrivateSystemProperties;
}
}
// Property returning the underlying lateBound object.
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public System.Management.ManagementBaseObject LateBoundObject {
get {
return curObj;
}
}
// ManagementScope of the object.
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public System.Management.ManagementScope Scope {
get {
if ((isEmbedded == false)) {
return PrivateLateBoundObject.Scope;
}
else {
return null;
}
}
set {
if ((isEmbedded == false)) {
PrivateLateBoundObject.Scope = value;
}
}
}
// Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property).
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool AutoCommit {
get {
return AutoCommitProp;
}
set {
AutoCommitProp = value;
}
}
// The ManagementPath of the underlying WMI object.
[Browsable(true)]
public System.Management.ManagementPath Path {
get {
if ((isEmbedded == false)) {
return PrivateLateBoundObject.Path;
}
else {
return null;
}
}
set {
if ((isEmbedded == false)) {
if ((CheckIfProperClass(null, value, null) != true)) {
throw new System.ArgumentException("Class name does not match.");
}
PrivateLateBoundObject.Path = value;
}
}
}
// Public static scope property which is used by the various methods.
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public static System.Management.ManagementScope StaticScope {
get {
return statMgmtScope;
}
set {
statMgmtScope = value;
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string Caption {
get {
return ((string)(curObj["Caption"]));
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string Data {
get {
return ((string)(curObj["Data"]));
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string Description {
get {
return ((string)(curObj["Description"]));
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string ElementName {
get {
return ((string)(curObj["ElementName"]));
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string InstanceID {
get {
return ((string)(curObj["InstanceID"]));
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string Name {
get {
return ((string)(curObj["Name"]));
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsSourceNull {
get {
if ((curObj["Source"] == null)) {
return true;
}
else {
return false;
}
}
}
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[TypeConverter(typeof(WMIValueTypeConverter))]
public ushort Source {
get {
if ((curObj["Source"] == null)) {
return System.Convert.ToUInt16(0);
}
return ((ushort)(curObj["Source"]));
}
}
private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) {
if (((path != null)
&& (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) {
return true;
}
else {
return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam));
}
}
private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) {
if (((theObj != null)
&& (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) {
return true;
}
else {
System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"]));
if ((parentClasses != null)) {
int count = 0;
for (count = 0; (count < parentClasses.Length); count = (count + 1)) {
if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) {
return true;
}
}
}
}
return false;
}
private bool ShouldSerializeSource() {
if ((this.IsSourceNull == false)) {
return true;
}
return false;
}
[Browsable(true)]
public void CommitObject() {
if ((isEmbedded == false)) {
PrivateLateBoundObject.Put();
}
}
[Browsable(true)]
public void CommitObject(System.Management.PutOptions putOptions) {
if ((isEmbedded == false)) {
PrivateLateBoundObject.Put(putOptions);
}
}
private void Initialize() {
AutoCommitProp = true;
isEmbedded = false;
}
private static string ConstructPath() {
string strPath = "ROOT\\virtualization\\v2:Msvm_KvpExchangeDataItem";
return strPath;
}
private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) {
Initialize();
if ((path != null)) {
if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) {
throw new System.ArgumentException("Class name does not match.");
}
}
PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions);
PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject);
curObj = PrivateLateBoundObject;
}
// Different overloads of GetInstances() help in enumerating instances of the WMI class.
public static KvpExchangeDataItemCollection GetInstances() {
return GetInstances(null, null, null);
}
public static KvpExchangeDataItemCollection GetInstances(string condition) {
return GetInstances(null, condition, null);
}
public static KvpExchangeDataItemCollection GetInstances(string[] selectedProperties) {
return GetInstances(null, null, selectedProperties);
}
public static KvpExchangeDataItemCollection GetInstances(string condition, string[] selectedProperties) {
return GetInstances(null, condition, selectedProperties);
}
public static KvpExchangeDataItemCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) {
if ((mgmtScope == null)) {
if ((statMgmtScope == null)) {
mgmtScope = new System.Management.ManagementScope();
mgmtScope.Path.NamespacePath = "root\\virtualization\\v2";
}
else {
mgmtScope = statMgmtScope;
}
}
System.Management.ManagementPath pathObj = new System.Management.ManagementPath();
pathObj.ClassName = "Msvm_KvpExchangeDataItem";
pathObj.NamespacePath = "root\\virtualization\\v2";
System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null);
if ((enumOptions == null)) {
enumOptions = new System.Management.EnumerationOptions();
enumOptions.EnsureLocatable = true;
}
return new KvpExchangeDataItemCollection(clsObject.GetInstances(enumOptions));
}
public static KvpExchangeDataItemCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) {
return GetInstances(mgmtScope, condition, null);
}
public static KvpExchangeDataItemCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) {
return GetInstances(mgmtScope, null, selectedProperties);
}
public static KvpExchangeDataItemCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) {
if ((mgmtScope == null)) {
if ((statMgmtScope == null)) {
mgmtScope = new System.Management.ManagementScope();
mgmtScope.Path.NamespacePath = "root\\virtualization\\v2";
}
else {
mgmtScope = statMgmtScope;
}
}
System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_KvpExchangeDataItem", condition, selectedProperties));
System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions();
enumOptions.EnsureLocatable = true;
ObjectSearcher.Options = enumOptions;
return new KvpExchangeDataItemCollection(ObjectSearcher.Get());
}
[Browsable(true)]
public static KvpExchangeDataItem CreateInstance() {
System.Management.ManagementScope mgmtScope = null;
if ((statMgmtScope == null)) {
mgmtScope = new System.Management.ManagementScope();
mgmtScope.Path.NamespacePath = CreatedWmiNamespace;
}
else {
mgmtScope = statMgmtScope;
}
System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName);
System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null);
return new KvpExchangeDataItem(tmpMgmtClass.CreateInstance());
}
[Browsable(true)]
public void Delete() {
PrivateLateBoundObject.Delete();
}
// Enumerator implementation for enumerating instances of the class.
public class KvpExchangeDataItemCollection : object, ICollection {
private ManagementObjectCollection privColObj;
public KvpExchangeDataItemCollection(ManagementObjectCollection objCollection) {
privColObj = objCollection;
}
public virtual int Count {
get {
return privColObj.Count;
}
}
public virtual bool IsSynchronized {
get {
return privColObj.IsSynchronized;
}
}
public virtual object SyncRoot {
get {
return this;
}
}
public virtual void CopyTo(System.Array array, int index) {
privColObj.CopyTo(array, index);
int nCtr;
for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) {
array.SetValue(new KvpExchangeDataItem(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr);
}
}
public virtual System.Collections.IEnumerator GetEnumerator() {
return new KvpExchangeDataItemEnumerator(privColObj.GetEnumerator());
}
public class KvpExchangeDataItemEnumerator : object, System.Collections.IEnumerator {
private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum;
public KvpExchangeDataItemEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) {
privObjEnum = objEnum;
}
public virtual object Current {
get {
return new KvpExchangeDataItem(((System.Management.ManagementObject)(privObjEnum.Current)));
}
}
public virtual bool MoveNext() {
return privObjEnum.MoveNext();
}
public virtual void Reset() {
privObjEnum.Reset();
}
}
}
// TypeConverter to handle null values for ValueType properties
public class WMIValueTypeConverter : TypeConverter {
private TypeConverter baseConverter;
private System.Type baseType;
public WMIValueTypeConverter(System.Type inBaseType) {
baseConverter = TypeDescriptor.GetConverter(inBaseType);
baseType = inBaseType;
}
public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) {
return baseConverter.CanConvertFrom(context, srcType);
}
public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) {
return baseConverter.CanConvertTo(context, destinationType);
}
public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) {
return baseConverter.ConvertFrom(context, culture, value);
}
public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) {
return baseConverter.CreateInstance(context, dictionary);
}
public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) {
return baseConverter.GetCreateInstanceSupported(context);
}
public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) {
return baseConverter.GetProperties(context, value, attributeVar);
}
public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) {
return baseConverter.GetPropertiesSupported(context);
}
public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) {
return baseConverter.GetStandardValues(context);
}
public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) {
return baseConverter.GetStandardValuesExclusive(context);
}
public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) {
return baseConverter.GetStandardValuesSupported(context);
}
public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) {
if ((baseType.BaseType == typeof(System.Enum))) {
if ((value.GetType() == destinationType)) {
return value;
}
if ((((value == null)
&& (context != null))
&& (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) {
return "NULL_ENUM_VALUE" ;
}
return baseConverter.ConvertTo(context, culture, value, destinationType);
}
if (((baseType == typeof(bool))
&& (baseType.BaseType == typeof(System.ValueType)))) {
if ((((value == null)
&& (context != null))
&& (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) {
return "";
}
return baseConverter.ConvertTo(context, culture, value, destinationType);
}
if (((context != null)
&& (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) {
return "";
}
return baseConverter.ConvertTo(context, culture, value, destinationType);
}
}
// Embedded class to represent WMI system Properties.
[TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))]
public class ManagementSystemProperties {
private System.Management.ManagementBaseObject PrivateLateBoundObject;
public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) {
PrivateLateBoundObject = ManagedObject;
}
[Browsable(true)]
public int GENUS {
get {
return ((int)(PrivateLateBoundObject["__GENUS"]));
}
}
[Browsable(true)]
public string CLASS {
get {
return ((string)(PrivateLateBoundObject["__CLASS"]));
}
}
[Browsable(true)]
public string SUPERCLASS {
get {
return ((string)(PrivateLateBoundObject["__SUPERCLASS"]));
}
}
[Browsable(true)]
public string DYNASTY {
get {
return ((string)(PrivateLateBoundObject["__DYNASTY"]));
}
}
[Browsable(true)]
public string RELPATH {
get {
return ((string)(PrivateLateBoundObject["__RELPATH"]));
}
}
[Browsable(true)]
public int PROPERTY_COUNT {
get {
return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"]));
}
}
[Browsable(true)]
public string[] DERIVATION {
get {
return ((string[])(PrivateLateBoundObject["__DERIVATION"]));
}
}
[Browsable(true)]
public string SERVER {
get {
return ((string)(PrivateLateBoundObject["__SERVER"]));
}
}
[Browsable(true)]
public string NAMESPACE {
get {
return ((string)(PrivateLateBoundObject["__NAMESPACE"]));
}
}
[Browsable(true)]
public string PATH {
get {
return ((string)(PrivateLateBoundObject["__PATH"]));
}
}
}
}
}

View File

@ -0,0 +1,20 @@
Classes were generated on a hyper-v server using the Visual Studio GUI, but you can do the same using
mgmtclassgen.exe. Below are some examples:
mgmtclassgen.exe Msvm_ComputerSystem /N root\virtualization /L CS /O CloudStack.Plugin.WmiWrappers /P ComputerSystem.cs
mgmtclassgen.exe Msvm_VirtualSystemManagementService /N root\virtualization /L CS /O CloudStack.Plugin.WmiWrappers /P VirtualSystemManagementService.cs
mgmtclassgen.exe Msvm_VirtualSystemGlobalSettingData /N root\virtualization /L CS /O CloudStack.Plugin.WmiWrappers /P VirtualSystemGlobalSettingData.cs
BUT, you have to tweak the generated code, because it does not deal with NULL method parameters properly.
E.g. when a method completes immediately, the returned out parameters include a "Job" property that has a NULL value.
The generated code will attempt to call ToString() on this NULL value.
ALSO, you have to tweak the generated code to expose useful details such as the WMI name for the class.
E.g. the generated code creates a wrapper called class ComputerSystem for WMI objects of class Msvm_ComputerSystem.
Thus, there is a mismatch in the class name and the corresponding WMI class, and the WMI class name is a private
constant static member. The tweak involves making this member public.

View File

@ -0,0 +1,167 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{DB824727-BDC3-437C-A364-7A811D8A160F}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>CloudStack.Plugin.WmiWrappers</RootNamespace>
<AssemblyName>WmiWrappers</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'NoUnitTestsDebug|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\NoUnitTestsDebug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'NoUnitTests|AnyCPU'">
<OutputPath>bin\NoUnitTests\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Management" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="ROOT.CIMV2.Win32_OperatingSystem.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="root.CIMV2.Win32_PerfFormattedData_Counters_ProcessorInformation.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="ROOT.CIMV2.Win32_Processor.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="ROOT.virtualization.Msvm_ComputerSystem.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="ROOT.virtualization.Msvm_ConcreteJob.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="ROOT.virtualization.Msvm_ExternalEthernetPort.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="ROOT.virtualization.Msvm_ImageManagementService.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="ROOT.virtualization.Msvm_MemorySettingData.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="ROOT.virtualization.Msvm_ProcessorSettingData.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="ROOT.virtualization.Msvm_ResourceAllocationSettingData.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="ROOT.virtualization.Msvm_SummaryInformation.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="ROOT.virtualization.Msvm_SwitchLANEndpoint.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="ROOT.virtualization.Msvm_SwitchPort.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="ROOT.virtualization.Msvm_SyntheticEthernetPort.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="ROOT.virtualization.Msvm_SyntheticEthernetPortSettingData.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="ROOT.virtualization.Msvm_VirtualSwitch.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="ROOT.virtualization.Msvm_VirtualSwitchManagementService.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="ROOT.virtualization.Msvm_VirtualSystemGlobalSettingData.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="ROOT.virtualization.Msvm_VirtualSystemManagementService.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="ROOT.virtualization.Msvm_VirtualSystemManagementServiceSettingData.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="ROOT.virtualization.Msvm_VirtualSystemSettingData.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="ROOT.virtualization.Msvm_VLANEndpoint.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="ROOT.virtualization.Msvm_VLANEndpointSettingData.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="ROOT.virtualization.Msvm_VmLANEndpoint.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="ROOT.virtualization.v2.Msvm_ComputerSystem.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="ROOT.virtualization.v2.Msvm_ConcreteJob.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="ROOT.virtualization.v2.Msvm_KvpExchangeComponent.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="ROOT.virtualization.v2.Msvm_KvpExchangeComponentSettingData.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="ROOT.virtualization.v2.Msvm_KvpExchangeDataItem.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="ROOT.virtualization.v2.Msvm_VirtualSystemManagementService.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="ROOT.virtualization.v2.Msvm_VirtualSystemSettingData.cs">
<SubType>Component</SubType>
</Compile>
</ItemGroup>
<ItemGroup>
<Content Include="Readme.txt" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@ -0,0 +1,22 @@
#!/bin/bash
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
export EnableNuGetPackageRestore=true
wget http://nuget.org/nuget.exe
mv nuget.exe ./DotNet/ServerResource/.nuget/NuGet.exe
chmod a+x ./DotNet/ServerResource/.nuget/NuGet.exe
xbuild /p:Configuration="NoUnitTests" /p:BuildWithMono="true" ./DotNet/ServerResource/ServerResource.sln

View File

@ -0,0 +1,35 @@
#Storage
#Tue Feb 12 10:08:17 GMT 2013
local.storage.path=E\:\\Disks\\Disks
cpus=8
resource=com.cloud.hypervisor.hyperv.resource.HypervResource
type=Routing
ipaddress=10.70.176.29
private.mac.address=101F742C6B88
# If localhost is used, mac address is blank.
#private.ip.address=127.0.0.1
#private.mac.address=
local.storage.uuid=5fe2bad3-d785-394e-9949-89786b8a63d2
capabilities=hvm
cpuspeed=2130
port=8250
hyperv.python.module.script=cloudstackcmds.py
memory=34359738368
host=camldonall01.citrite.net
pod=1
gateway.ip.address=10.70.176.1
guid=16f85622-4508-415e-b13a-49a39bb14e4d
#guid=generate_from_private.ip.address
cluster=2
zone=1
local.secondary.storage.path=c\:\\Secondary
workers=5
agent.executable=C\:\\cygwin\\home\\Administrator\\github\\cshv3\\plugins\\hypervisors\\hyperv\\DotNET\\ServerResource\\AgentShell\\bin\\Debug\\AgentShell.exe
private.ip.netmask=255.255.240.0
HypervResource.id=5
hyperv.python.module.dir=C\:\\cygwin\\home\\Administrator\\github\\cshv3\\plugins\\hypervisors\\hyperv\\scripts\\hyperv\\
DefaultVirtualDiskFolder=E\:\\Disks\\
TestCoreCount=8
TestCoreMhz=2133
TestMemoryMb=34350288896
TestDom0MinMemoryMb=2147483648

View File

@ -0,0 +1,55 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
#instance=AH
#private.macaddr.start=00:16:3e:77:01:01
#private.ipaddr.start=192.168.166.128
#instance=KM
#private.macaddr.start=00:16:3e:77:02:01
#private.ipaddr.start=192.168.167.128
#instance=KY
#private.macaddr.start=00:16:3e:77:03:01
#private.ipaddr.start=192.168.168.128
#instance=WC
#private.macaddr.start=00:16:3e:77:04:01
#private.ipaddr.start=192.168.169.128
#instance=CV
#private.macaddr.start=00:16:3e:77:05:01
#private.ipaddr.start=192.168.170.128
#instance=KS
#private.macaddr.start=00:16:3e:77:06:01
#private.ipaddr.start=192.168.171.128
#instance=ES
#private.macaddr.start=00:16:3e:77:07:01
#private.ipaddr.start=192.168.172.128
#instance=RC
#private.macaddr.start=00:16:3e:77:08:01
#private.ipaddr.start=192.168.173.128
#instance=AX
#private.macaddr.start=00:16:3e:77:09:01
#private.ipaddr.start=192.168.174.128
private.macaddr.start=@private.macaddr.start@
private.ipaddr.start=@private.ipaddr.start@

View File

@ -0,0 +1,21 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
# management server compile-time environment parameters
paths.pid=@PIDDIR@
paths.script=@COMMONLIBDIR@

View File

@ -0,0 +1,93 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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.
-->
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
<!-- ================================= -->
<!-- Preserve messages in a local file -->
<!-- ================================= -->
<!-- A time/date based rolling appender -->
<appender name="FILE" class="org.apache.log4j.rolling.RollingFileAppender">
<param name="Append" value="true"/>
<param name="Threshold" value="TRACE"/>
<rollingPolicy class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
<param name="FileNamePattern" value="log/@AGENTLOG@.%d{yyyy-MM-dd}.gz"/>
<param name="ActiveFileName" value="log/@AGENTLOG@"/>
</rollingPolicy>
<layout class="org.apache.log4j.EnhancedPatternLayout">
<param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{3}] (%t:%x) %m%n"/>
</layout>
</appender>
<!-- ============================== -->
<!-- Append messages to the console -->
<!-- ============================== -->
<appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
<param name="Target" value="System.out"/>
<param name="Threshold" value="TRACE"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{ISO8601}{GMT} %-5p [%c{3}] (%t:%x) %m%n"/>
</layout>
</appender>
<!-- ================ -->
<!-- Limit categories -->
<!-- ================ -->
<category name="com.cloud">
<priority value="TRACE"/>
</category>
<category name="com.cloud.agent.metrics">
<priority value="TRACE"/>
</category>
<category name="com.cloud.agent.resource.computing.ComputingResource$StorageMonitorTask">
<priority value="TRACE"/>
</category>
<!-- Limit the org.apache category to TRACE as its DEBUG is verbose -->
<category name="org.apache">
<priority value="TRACE"/>
</category>
<category name="org">
<priority value="TRACE"/>
</category>
<category name="net">
<priority value="TRACE"/>
</category>
<!-- ======================= -->
<!-- Setup the Root category -->
<!-- ======================= -->
<root>
<level value="TRACE"/>
<appender-ref ref="CONSOLE"/>
<appender-ref ref="FILE"/>
</root>
</log4j:configuration>

View File

@ -0,0 +1,93 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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.
-->
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
<!-- ================================= -->
<!-- Preserve messages in a local file -->
<!-- ================================= -->
<!-- A time/date based rolling appender -->
<appender name="FILE" class="org.apache.log4j.rolling.RollingFileAppender">
<param name="Append" value="true"/>
<param name="Threshold" value="INFO"/>
<rollingPolicy class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
<param name="FileNamePattern" value="@AGENTLOG@.%d{yyyy-MM-dd}.gz"/>
<param name="ActiveFileName" value="@AGENTLOG@"/>
</rollingPolicy>
<layout class="org.apache.log4j.EnhancedPatternLayout">
<param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{3}] (%t:%x) %m%n"/>
</layout>
</appender>
<!-- ============================== -->
<!-- Append messages to the console -->
<!-- ============================== -->
<appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
<param name="Target" value="System.out"/>
<param name="Threshold" value="INFO"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{ISO8601}{GMT} %-5p [%c{3}] (%t:%x) %m%n"/>
</layout>
</appender>
<!-- ================ -->
<!-- Limit categories -->
<!-- ================ -->
<category name="com.cloud">
<priority value="INFO"/>
</category>
<category name="com.cloud.agent.metrics">
<priority value="INFO"/>
</category>
<category name="com.cloud.agent.resource.computing.ComputingResource$StorageMonitorTask">
<priority value="INFO"/>
</category>
<!-- Limit the org.apache category to INFO as its DEBUG is verbose -->
<category name="org.apache">
<priority value="INFO"/>
</category>
<category name="org">
<priority value="INFO"/>
</category>
<category name="net">
<priority value="INFO"/>
</category>
<!-- ======================= -->
<!-- Setup the Root category -->
<!-- ======================= -->
<root>
<level value="INFO"/>
<appender-ref ref="CONSOLE"/>
<appender-ref ref="FILE"/>
</root>
</log4j:configuration>

View File

@ -0,0 +1,93 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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.
-->
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
<!-- ================================= -->
<!-- Preserve messages in a local file -->
<!-- ================================= -->
<!-- A time/date based rolling appender -->
<appender name="FILE" class="org.apache.log4j.rolling.RollingFileAppender">
<param name="Append" value="true"/>
<param name="Threshold" value="TRACE"/>
<rollingPolicy class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
<param name="FileNamePattern" value="log/@AGENTLOG@.%d{yyyy-MM-dd}.gz"/>
<param name="ActiveFileName" value="log/@AGENTLOG@"/>
</rollingPolicy>
<layout class="org.apache.log4j.EnhancedPatternLayout">
<param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{3}] (%t:%x) %m%n"/>
</layout>
</appender>
<!-- ============================== -->
<!-- Append messages to the console -->
<!-- ============================== -->
<appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
<param name="Target" value="System.out"/>
<param name="Threshold" value="TRACE"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{ISO8601}{GMT} %-5p [%c{3}] (%t:%x) %m%n"/>
</layout>
</appender>
<!-- ================ -->
<!-- Limit categories -->
<!-- ================ -->
<category name="com.cloud">
<priority value="TRACE"/>
</category>
<category name="com.cloud.agent.metrics">
<priority value="TRACE"/>
</category>
<category name="com.cloud.agent.resource.computing.ComputingResource$StorageMonitorTask">
<priority value="TRACE"/>
</category>
<!-- Limit the org.apache category to TRACE as its DEBUG is verbose -->
<category name="org.apache">
<priority value="TRACE"/>
</category>
<category name="org">
<priority value="TRACE"/>
</category>
<category name="net">
<priority value="TRACE"/>
</category>
<!-- ======================= -->
<!-- Setup the Root category -->
<!-- ======================= -->
<root>
<level value="TRACE"/>
<appender-ref ref="CONSOLE"/>
<appender-ref ref="FILE"/>
</root>
</log4j:configuration>

View File

@ -0,0 +1,158 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>cloud-plugin-hypervisor-hyperv</artifactId>
<name>Apache CloudStack Plugin - Hypervisor Hyper-V</name>
<parent>
<groupId>org.apache.cloudstack</groupId>
<artifactId>cloudstack-plugins</artifactId>
<version>4.3.0-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<properties>
<skipTests>true</skipTests>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.cloudstack</groupId>
<artifactId>cloud-agent</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.cloudstack</groupId>
<artifactId>cloud-core</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty</artifactId>
<version>6.1.26</version>
</dependency>
<dependency>
<groupId>org.apache.cloudstack</groupId>
<artifactId>cloud-utils</artifactId>
<version>${project.version}</version>
<classifier>tests</classifier>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<defaultGoal>install</defaultGoal>
<sourceDirectory>src</sourceDirectory>
<testSourceDirectory>test</testSourceDirectory>
<resources>
<resource>
<directory>conf</directory>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<configuration>
<executable>java</executable>
<mainClass>com.cloud.agent.AgentShell</mainClass>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>test-jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12</version>
<configuration>
<!-- Exclude tests that require an agent, they appear under a different profile -->
<excludes>
<exclude>**/HypervDirectConnectResourceTest.*</exclude>
</excludes>
<includes>
<include>none</include>
</includes>
<skipTests>${skipTests}</skipTests>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<!-- Hyper-V plugin is built using mono -->
<profile>
<id>hyperv-agent</id>
<activation>
<property>
<name>hyperv-agent</name>
</property>
</activation>
<!-- <dependencies>
<dependency>
<groupId>org.apache.cloudstack</groupId>
<artifactId>cloud-plugin-hypervisor-hyperv</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies> -->
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<phase>compile</phase>
<goals>
<goal>exec</goal>
</goals>
</execution>
</executions>
<configuration>
<executable>bash</executable>
<arguments>
<argument>./buildagent.sh</argument>
</arguments>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12</version>
<configuration>
<excludes>
<exclude>none</exclude>
</excludes>
<includes>
<include>**/HypervDirectConnectResourceTest.java</include>
</includes>
<skipTests>${skipTests}</skipTests>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>

View File

@ -0,0 +1,8 @@
#!/bin/bash
mvn -P developer -pl developer -Ddeploydb
cp client/target/cloud-client-ui-4.2.0-SNAPSHOT/WEB-INF/classes/log4j{-cloud,}.xml
mysql --user=root --password="" cloud -e "update configuration set value='false' where name='developer';"
mysql --user=root --password="" cloud -e "INSERT INTO configuration (instance, name,value) VALUE('DEFAULT','system.vm.use.local.storage', 'true');"
update template_view set url='http://10.70.176.29/pub/systemvmtemplate-2013-07-04-master-hyperv.vhd' where name='SystemVM Template (HyperV)';
export MAVEN_OPTS="-XX:MaxPermSize=256m -Xmx1g"
mvn -pl :cloud-client-ui jetty:run

View File

@ -0,0 +1,467 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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.
package com.cloud.hypervisor.hyperv.discoverer;
import java.net.InetAddress;
import java.net.URI;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.ejb.Local;
import javax.inject.Inject;
import javax.naming.ConfigurationException;
import org.apache.log4j.Logger;
import com.cloud.agent.AgentManager;
import com.cloud.agent.Listener;
import com.cloud.agent.api.AgentControlAnswer;
import com.cloud.agent.api.AgentControlCommand;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.ReadyCommand;
import com.cloud.agent.api.SetupAnswer;
import com.cloud.agent.api.SetupCommand;
import com.cloud.agent.api.StartupCommand;
import com.cloud.agent.api.StartupRoutingCommand;
import com.cloud.alert.AlertManager;
import com.cloud.dc.ClusterDetailsDao;
import com.cloud.dc.ClusterVO;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.HostPodVO;
import com.cloud.dc.dao.ClusterDao;
import com.cloud.dc.dao.DataCenterDao;
import com.cloud.dc.dao.HostPodDao;
import com.cloud.exception.AgentUnavailableException;
import com.cloud.exception.ConnectionException;
import com.cloud.exception.DiscoveryException;
import com.cloud.exception.OperationTimedoutException;
import com.cloud.host.Host;
import com.cloud.host.HostEnvironment;
import com.cloud.host.HostVO;
import com.cloud.host.Status;
import com.cloud.host.dao.HostDao;
import com.cloud.hypervisor.Hypervisor;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.hypervisor.hyperv.resource.HypervDirectConnectResource;
import com.cloud.resource.Discoverer;
import com.cloud.resource.DiscovererBase;
import com.cloud.resource.ResourceManager;
import com.cloud.resource.ResourceStateAdapter;
import com.cloud.resource.ServerResource;
import com.cloud.resource.UnableDeleteHostException;
/**
* Methods to discover and managem a Hyper-V agent. Prepares a
* HypervDirectConnectResource corresponding to the agent on a Hyper-V
* hypervisor and manages its lifecycle.
*/
@Local(value = Discoverer.class)
public class HypervServerDiscoverer extends DiscovererBase implements
Discoverer, Listener, ResourceStateAdapter {
private static final Logger s_logger = Logger
.getLogger(HypervServerDiscoverer.class);
@Inject
private HostDao _hostDao = null;
@Inject
private ClusterDao _clusterDao;
@Inject
private ClusterDetailsDao _clusterDetailsDao;
@Inject
private ResourceManager _resourceMgr;
@Inject
private HostPodDao _podDao;
@Inject
private DataCenterDao _dcDao;
// TODO: AgentManager and AlertManager not being used to transmit info,
// may want to reconsider.
@Inject
private AgentManager _agentMgr;
@Inject
private AlertManager _alertMgr;
// Listener interface methods
@Override
public final boolean processAnswers(final long agentId, final long seq,
final Answer[] answers) {
return false;
}
@Override
public final boolean processCommands(final long agentId, final long seq,
final Command[] commands) {
return false;
}
@Override
public final AgentControlAnswer processControlCommand(final long agentId,
final AgentControlCommand cmd) {
return null;
}
@Override
public final void processConnect(final Host agent,
final StartupCommand cmd, final boolean forRebalance)
throws ConnectionException {
// Limit the commands we can process
if (!(cmd instanceof StartupRoutingCommand)) {
return;
}
StartupRoutingCommand startup = (StartupRoutingCommand) cmd;
// assert
if (startup.getHypervisorType() != HypervisorType.Hyperv) {
s_logger.debug("Not Hyper-V hypervisor, so moving on.");
return;
}
long agentId = agent.getId();
HostVO host = _hostDao.findById(agentId);
// Our Hyper-V machines are not participating in pools, and the pool id
// we provide them is not persisted.
// This means the pool id can vary.
ClusterVO cluster = _clusterDao.findById(host.getClusterId());
if (cluster.getGuid() == null) {
cluster.setGuid(startup.getPool());
_clusterDao.update(cluster.getId(), cluster);
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Setting up host " + agentId);
}
HostEnvironment env = new HostEnvironment();
SetupCommand setup = new SetupCommand(env);
if (!host.isSetup()) {
setup.setNeedSetup(true);
}
try {
SetupAnswer answer = (SetupAnswer) _agentMgr.send(agentId, setup);
if (answer != null && answer.getResult()) {
host.setSetup(true);
// TODO: clean up magic numbers below
host.setLastPinged((System.currentTimeMillis() >> 10) - 5 * 60);
_hostDao.update(host.getId(), host);
if (answer.needReconnect()) {
throw new ConnectionException(false,
"Reinitialize agent after setup.");
}
return;
} else {
String reason = answer.getDetails();
if (reason == null) {
reason = " details were null";
}
s_logger.warn("Unable to setup agent " + agentId + " due to "
+ reason);
}
// Error handling borrowed from XcpServerDiscoverer, may need to be
// updated.
} catch (AgentUnavailableException e) {
s_logger.warn("Unable to setup agent " + agentId
+ " because it became unavailable.", e);
} catch (OperationTimedoutException e) {
s_logger.warn("Unable to setup agent " + agentId
+ " because it timed out", e);
}
throw new ConnectionException(true, "Reinitialize agent after setup.");
}
@Override
public final boolean processDisconnect(final long agentId,
final Status state) {
return false;
}
@Override
public final boolean isRecurring() {
return false;
}
@Override
public final int getTimeout() {
return 0;
}
@Override
public final boolean processTimeout(final long agentId, final long seq) {
return false;
}
// End Listener implementation
// Returns server component used by server manager to operate the plugin.
// Server component is a ServerResource. If a connected agent is used, the
// ServerResource is
// ignored in favour of another created in response to
@Override
public final Map<? extends ServerResource, Map<String, String>> find(
final long dcId, final Long podId, final Long clusterId,
final URI uri, final String username, final String password,
final List<String> hostTags) throws DiscoveryException {
if (s_logger.isInfoEnabled()) {
s_logger.info("Discover host. dc(zone): " + dcId + ", pod: "
+ podId + ", cluster: " + clusterId + ", uri host: "
+ uri.getHost());
}
// Assertions
if (podId == null) {
if (s_logger.isInfoEnabled()) {
s_logger.info("No pod is assigned, skipping the discovery in"
+ " Hyperv discoverer");
}
return null;
}
ClusterVO cluster = _clusterDao.findById(clusterId); // ClusterVO exists
// in the
// database
if (cluster == null) {
if (s_logger.isInfoEnabled()) {
s_logger.info("No cluster in database for cluster id "
+ clusterId);
}
return null;
}
if (cluster.getHypervisorType() != HypervisorType.Hyperv) {
if (s_logger.isInfoEnabled()) {
s_logger.info("Cluster " + clusterId
+ "is not for Hyperv hypervisors");
}
return null;
}
if (!uri.getScheme().equals("http")) {
String msg = "urlString is not http so we're not taking care of"
+ " the discovery for this: " + uri;
s_logger.debug(msg);
return null;
}
try {
String hostname = uri.getHost();
InetAddress ia = InetAddress.getByName(hostname);
String agentIp = ia.getHostAddress();
String uuidSeed = agentIp;
String guidWithTail = calcServerResourceGuid(uuidSeed)
+ "-HypervResource";
if (_resourceMgr.findHostByGuid(guidWithTail) != null) {
s_logger.debug("Skipping " + agentIp + " because "
+ guidWithTail + " is already in the database.");
return null;
}
s_logger.info("Creating"
+ HypervDirectConnectResource.class.getName()
+ " HypervDummyResourceBase for zone/pod/cluster " + dcId
+ "/" + podId + "/" + clusterId);
// Some Hypervisors organise themselves in pools.
// The startup command tells us what pool they are using.
// In the meantime, we have to place a GUID corresponding to the
// pool in the database
// This GUID may change.
if (cluster.getGuid() == null) {
cluster.setGuid(UUID.nameUUIDFromBytes(
String.valueOf(clusterId).getBytes()).toString());
_clusterDao.update(clusterId, cluster);
}
// Settings required by all server resources managing a hypervisor
Map<String, Object> params = new HashMap<String, Object>();
params.put("zone", Long.toString(dcId));
params.put("pod", Long.toString(podId));
params.put("cluster", Long.toString(clusterId));
params.put("guid", guidWithTail);
params.put("ipaddress", agentIp);
// Hyper-V specific settings
Map<String, String> details = new HashMap<String, String>();
details.put("url", uri.getHost());
details.put("username", username);
details.put("password", password);
details.put("cluster.guid", cluster.getGuid());
params.putAll(details);
HypervDirectConnectResource resource =
new HypervDirectConnectResource();
resource.configure(agentIp, params);
// Assert
// TODO: test by using bogus URL and bogus virtual path in URL
ReadyCommand ping = new ReadyCommand();
Answer pingAns = resource.executeRequest(ping);
if (pingAns == null || !pingAns.getResult()) {
String errMsg =
"Agent not running, or no route to agent on at "
+ uri;
s_logger.debug(errMsg);
throw new DiscoveryException(errMsg);
}
Map<HypervDirectConnectResource, Map<String, String>> resources =
new HashMap<HypervDirectConnectResource,
Map<String, String>>();
resources.put(resource, details);
// TODO: does the resource have to create a connection?
return resources;
} catch (ConfigurationException e) {
_alertMgr.sendAlert(AlertManager.ALERT_TYPE_HOST, dcId, podId,
"Unable to add " + uri.getHost(),
"Error is " + e.getMessage());
s_logger.warn("Unable to instantiate " + uri.getHost(), e);
} catch (UnknownHostException e) {
_alertMgr.sendAlert(AlertManager.ALERT_TYPE_HOST, dcId, podId,
"Unable to add " + uri.getHost(),
"Error is " + e.getMessage());
s_logger.warn("Unable to instantiate " + uri.getHost(), e);
} catch (Exception e) {
String msg = " can't setup agent, due to " + e.toString() + " - "
+ e.getMessage();
s_logger.warn(msg);
}
return null;
}
/**
* Encapsulate GUID calculation in public method to allow access to test
* programs. Works by converting a string to a GUID using
* UUID.nameUUIDFromBytes
*
* @param uuidSeed
* string to use to generate GUID
*
* @return GUID in form of a string.
*/
public static String calcServerResourceGuid(final String uuidSeed) {
String guid = UUID.nameUUIDFromBytes(uuidSeed.getBytes()).toString();
return guid;
}
// Adapter implementation: (facilitates plug in loading)
// Required because Discoverer extends Adapter
// Overrides Adapter.configure to always return true
// Inherit Adapter.getName
// Inherit Adapter.stop
// Inherit Adapter.start
@Override
public final boolean configure(final String name,
final Map<String, Object> params) throws ConfigurationException {
super.configure(name, params);
// TODO: allow timeout on we HTTPRequests to be configured
_agentMgr.registerForHostEvents(this, true, false, true);
_resourceMgr.registerResourceStateAdapter(this.getClass()
.getSimpleName(), this);
return true;
}
// end of Adapter
@Override
public void postDiscovery(final List<HostVO> hosts, final long msId)
throws DiscoveryException {
}
@Override
public final Hypervisor.HypervisorType getHypervisorType() {
return Hypervisor.HypervisorType.Hyperv;
}
// TODO: verify that it is okay to return true on null hypervisor
@Override
public final boolean matchHypervisor(final String hypervisor) {
if (hypervisor == null) {
return true;
}
return Hypervisor.HypervisorType.Hyperv.toString().equalsIgnoreCase(
hypervisor);
}
// end of Discoverer
// ResourceStateAdapter
@Override
public final HostVO createHostVOForConnectedAgent(final HostVO host,
final StartupCommand[] cmd) {
return null;
}
// TODO: add test for method
@Override
public final HostVO createHostVOForDirectConnectAgent(final HostVO host,
final StartupCommand[] startup, final ServerResource resource,
final Map<String, String> details, final List<String> hostTags) {
StartupCommand firstCmd = startup[0];
if (!(firstCmd instanceof StartupRoutingCommand)) {
return null;
}
StartupRoutingCommand ssCmd = ((StartupRoutingCommand) firstCmd);
if (ssCmd.getHypervisorType() != HypervisorType.Hyperv) {
return null;
}
s_logger.info("Host: " + host.getName()
+ " connected with hypervisor type: " + HypervisorType.Hyperv
+ ". Checking CIDR...");
HostPodVO pod = _podDao.findById(host.getPodId());
DataCenterVO dc = _dcDao.findById(host.getDataCenterId());
_resourceMgr.checkCIDR(pod, dc, ssCmd.getPrivateIpAddress(),
ssCmd.getPrivateNetmask());
return _resourceMgr.fillRoutingHostVO(host, ssCmd,
HypervisorType.Hyperv, details, hostTags);
}
// TODO: add test for method
@Override
public final DeleteHostAnswer deleteHost(final HostVO host,
final boolean isForced, final boolean isForceDeleteStorage)
throws UnableDeleteHostException {
// assert
if (host.getType() != Host.Type.Routing
|| host.getHypervisorType() != HypervisorType.Hyperv) {
return null;
}
_resourceMgr.deleteRoutingHost(host, isForced, isForceDeleteStorage);
return new DeleteHostAnswer(true);
}
@Override
public final boolean stop() {
_resourceMgr.unregisterResourceStateAdapter(this.getClass()
.getSimpleName());
return super.stop();
}
// end of ResourceStateAdapter
}

View File

@ -0,0 +1,68 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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.
package com.cloud.hypervisor.hyperv.guru;
import javax.ejb.Local;
import javax.inject.Inject;
import com.cloud.agent.api.to.VirtualMachineTO;
import com.cloud.hypervisor.HypervisorGuru;
import com.cloud.hypervisor.HypervisorGuruBase;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.storage.GuestOSVO;
import com.cloud.storage.dao.GuestOSDao;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachineProfile;
/**
* Implementation of Hypervisor guru for Hyper-V.
**/
@Local(value = HypervisorGuru.class)
public class HypervGuru extends HypervisorGuruBase implements HypervisorGuru {
@Inject
private GuestOSDao _guestOsDao;
@Override
public final HypervisorType getHypervisorType() {
return HypervisorType.Hyperv;
}
/**
* Prevent direct creation.
*/
protected HypervGuru() {
super();
}
@Override
public final VirtualMachineTO implement(
VirtualMachineProfile vm) {
VirtualMachineTO to = toVirtualMachineTO(vm);
// Determine the VM's OS description
GuestOSVO guestOS = _guestOsDao.findById(vm.getVirtualMachine()
.getGuestOSId());
to.setOs(guestOS.getDisplayName());
return to;
}
@Override
public final boolean trackVmHostChange() {
return false;
}
}

View File

@ -0,0 +1,454 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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.
package com.cloud.hypervisor.hyperv.resource;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import javax.naming.ConfigurationException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.PingCommand;
import com.cloud.agent.api.PingRoutingCommand;
import com.cloud.agent.api.StartupCommand;
import com.cloud.agent.api.StartupRoutingCommand;
import com.cloud.agent.api.StartupStorageCommand;
import com.cloud.agent.api.UnsupportedAnswer;
import com.cloud.agent.api.StartupRoutingCommand.VmState;
import com.cloud.host.Host.Type;
import com.cloud.hypervisor.Hypervisor;
import com.cloud.network.Networks.RouterPrivateIpStrategy;
import com.cloud.resource.ServerResource;
import com.cloud.resource.ServerResourceBase;
import com.cloud.serializer.GsonHelper;
import com.google.gson.Gson;
/**
* Implementation of dummy resource to be returned from discoverer.
**/
public class HypervDirectConnectResource extends ServerResourceBase implements
ServerResource {
public static final int DEFAULT_AGENT_PORT = 8250;
private static final Logger s_logger = Logger
.getLogger(HypervDirectConnectResource.class.getName());
private static final Gson s_gson = GsonHelper.getGson();
private String _zoneId;
private String _podId;
private String _clusterId;
private String _guid;
private String _agentIp;
private int _port = DEFAULT_AGENT_PORT;
private String _clusterGuid;
// Used by initialize to assert object configured before
// initialize called.
private boolean _configureCalled = false;
private String _username;
private String _password;
@Override
public final Type getType() {
return Type.Routing;
}
@Override
public final StartupCommand[] initialize() {
// assert
if (!_configureCalled) {
String errMsg =
this.getClass().getName()
+ " requires configure() be called before"
+ " initialize()";
s_logger.error(errMsg);
}
// Create default StartupRoutingCommand, then customise
StartupRoutingCommand defaultStartRoutCmd =
new StartupRoutingCommand(0, 0, 0, 0, null,
Hypervisor.HypervisorType.Hyperv,
RouterPrivateIpStrategy.HostLocal,
new HashMap<String, VmState>());
// Identity within the data centre is decided by CloudStack kernel,
// and passed via ServerResource.configure()
defaultStartRoutCmd.setDataCenter(_zoneId);
defaultStartRoutCmd.setPod(_podId);
defaultStartRoutCmd.setCluster(_clusterId);
defaultStartRoutCmd.setGuid(_guid);
defaultStartRoutCmd.setName(_name);
defaultStartRoutCmd.setPrivateIpAddress(_agentIp);
defaultStartRoutCmd.setStorageIpAddress(_agentIp);
defaultStartRoutCmd.setPool(_clusterGuid);
s_logger.debug("Generated StartupRoutingCommand for _agentIp \""
+ _agentIp + "\"");
// TODO: does version need to be hard coded.
defaultStartRoutCmd.setVersion("4.2.0");
// Specifics of the host's resource capacity and network configuration
// comes from the host itself. CloudStack sanity checks network
// configuration
// and uses capacity info for resource allocation.
Command[] startCmds =
requestStartupCommand(new Command[] {defaultStartRoutCmd});
// TODO: may throw, is this okay?
StartupRoutingCommand startCmd = (StartupRoutingCommand) startCmds[0];
// Assert that host identity is consistent with existing values.
if (startCmd == null) {
String errMsg =
String.format("Host %s (IP %s)"
+ "did not return a StartupRoutingCommand",
_name, _agentIp);
s_logger.error(errMsg);
// TODO: valid to return null, or should we throw?
return null;
}
if (!startCmd.getDataCenter().equals(
defaultStartRoutCmd.getDataCenter())) {
String errMsg =
String.format(
"Host %s (IP %s) changed zone/data center. Was "
+ defaultStartRoutCmd.getDataCenter()
+ " NOW its " + startCmd.getDataCenter(),
_name, _agentIp);
s_logger.error(errMsg);
// TODO: valid to return null, or should we throw?
return null;
}
if (!startCmd.getPod().equals(defaultStartRoutCmd.getPod())) {
String errMsg =
String.format("Host %s (IP %s) changed pod. Was "
+ defaultStartRoutCmd.getPod() + " NOW its "
+ startCmd.getPod(), _name, _agentIp);
s_logger.error(errMsg);
// TODO: valid to return null, or should we throw?
return null;
}
if (!startCmd.getCluster().equals(defaultStartRoutCmd.getCluster())) {
String errMsg =
String.format("Host %s (IP %s) changed cluster. Was "
+ defaultStartRoutCmd.getCluster() + " NOW its "
+ startCmd.getCluster(), _name, _agentIp);
s_logger.error(errMsg);
// TODO: valid to return null, or should we throw?
return null;
}
if (!startCmd.getGuid().equals(defaultStartRoutCmd.getGuid())) {
String errMsg =
String.format("Host %s (IP %s) changed guid. Was "
+ defaultStartRoutCmd.getGuid() + " NOW its "
+ startCmd.getGuid(), _name, _agentIp);
s_logger.error(errMsg);
// TODO: valid to return null, or should we throw?
return null;
}
if (!startCmd.getPrivateIpAddress().equals(
defaultStartRoutCmd.getPrivateIpAddress())) {
String errMsg =
String.format("Host %s (IP %s) IP address. Was "
+ defaultStartRoutCmd.getPrivateIpAddress()
+ " NOW its " + startCmd.getPrivateIpAddress(),
_name, _agentIp);
s_logger.error(errMsg);
// TODO: valid to return null, or should we throw?
return null;
}
if (!startCmd.getName().equals(defaultStartRoutCmd.getName())) {
String errMsg =
String.format(
"Host %s (IP %s) name. Was " + startCmd.getName()
+ " NOW its "
+ defaultStartRoutCmd.getName(), _name,
_agentIp);
s_logger.error(errMsg);
// TODO: valid to return null, or should we throw?
return null;
}
// Host will also supply details of an existing StoragePool if it has
// been configured with one.
//
// NB: if the host was configured
// with a local storage pool, CloudStack may not be able to use it
// unless
// it is has service offerings configured to recognise this storage
// type.
StartupStorageCommand storePoolCmd = null;
if (startCmds.length > 1) {
storePoolCmd = (StartupStorageCommand) startCmds[1];
// TODO: is this assertion required?
if (storePoolCmd == null) {
String frmtStr =
"Host %s (IP %s) sent incorrect Command, "
+ "second parameter should be a "
+ "StartupStorageCommand";
String errMsg = String.format(frmtStr, _name, _agentIp);
s_logger.error(errMsg);
// TODO: valid to return null, or should we throw?
return null;
}
s_logger.info("Host " + _name + " (IP " + _agentIp
+ ") already configured with a storeage pool, details "
+ s_gson.toJson(startCmds[1]));
} else {
s_logger.info("Host " + _name + " (IP " + _agentIp
+ ") already configured with a storeage pool, details ");
}
return new StartupCommand[] {startCmd, storePoolCmd};
}
@Override
public final PingCommand getCurrentStatus(final long id) {
PingCommand pingCmd = new PingRoutingCommand(getType(), id, null);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Ping host " + _name + " (IP " + _agentIp + ")");
}
Answer pingAns = this.executeRequest(pingCmd);
if (pingAns == null || !pingAns.getResult()) {
s_logger.info("Cannot ping host " + _name + " (IP " + _agentIp
+ "), pingAns (blank means null) is:" + pingAns);
return null;
}
return pingCmd;
}
// TODO: Is it valid to return NULL, or should we throw on error?
// Returns StartupCommand with fields revised with values known only to the
// host
public final Command[] requestStartupCommand(final Command[] cmd) {
// Set HTTP POST destination URI
// Using java.net.URI, see
// http://docs.oracle.com/javase/1.5.0/docs/api/java/net/URI.html
URI agentUri = null;
try {
String cmdName = StartupCommand.class.getName();
agentUri =
new URI("http", null, _agentIp, _port,
"/api/HypervResource/" + cmdName, null, null);
} catch (URISyntaxException e) {
// TODO add proper logging
String errMsg = "Could not generate URI for Hyper-V agent";
s_logger.error(errMsg, e);
return null;
}
String incomingCmd = postHttpRequest(s_gson.toJson(cmd), agentUri);
if (incomingCmd == null) {
return null;
}
Command[] result = null;
try {
result = s_gson.fromJson(incomingCmd, Command[].class);
} catch (Exception ex) {
String errMsg = "Failed to deserialize Command[] " + incomingCmd;
s_logger.error(errMsg, ex);
}
s_logger.debug("requestStartupCommand received response "
+ s_gson.toJson(result));
if (result.length > 0) {
return result;
}
return null;
}
// TODO: Is it valid to return NULL, or should we throw on error?
@Override
public final Answer executeRequest(final Command cmd) {
// Set HTTP POST destination URI
// Using java.net.URI, see
// http://docs.oracle.com/javase/1.5.0/docs/api/java/net/URI.html
URI agentUri = null;
try {
String cmdName = cmd.getClass().getName();
agentUri =
new URI("http", null, _agentIp, _port,
"/api/HypervResource/" + cmdName, null, null);
} catch (URISyntaxException e) {
// TODO add proper logging
String errMsg = "Could not generate URI for Hyper-V agent";
s_logger.error(errMsg, e);
return null;
}
String ansStr = postHttpRequest(s_gson.toJson(cmd), agentUri);
if (ansStr == null) {
return null;
}
// Only Answer instances are returned by remote agents.
// E.g. see Response.getAnswers()
Answer[] result = s_gson.fromJson(ansStr, Answer[].class);
s_logger.debug("executeRequest received response "
+ s_gson.toJson(result));
if (result.length > 0) {
return result[0];
}
return null;
}
public static String postHttpRequest(final String jsonCmd,
final URI agentUri) {
// Using Apache's HttpClient for HTTP POST
// Java-only approach discussed at on StackOverflow concludes with
// comment to use Apache HttpClient
// http://stackoverflow.com/a/2793153/939250, but final comment is to
// use Apache.
s_logger.debug("POST request to" + agentUri.toString()
+ " with contents" + jsonCmd);
// Create request
HttpClient httpClient = new DefaultHttpClient();
String result = null;
// TODO: are there timeout settings and worker thread settings to tweak?
try {
HttpPost request = new HttpPost(agentUri);
// JSON encode command
// Assumes command sits comfortably in a string, i.e. not used for
// large data transfers
StringEntity cmdJson = new StringEntity(jsonCmd);
request.addHeader("content-type", "application/json");
request.setEntity(cmdJson);
s_logger.debug("Sending cmd to " + agentUri.toString()
+ " cmd data:" + jsonCmd);
HttpResponse response = httpClient.execute(request);
// Unsupported commands will not route.
if (response.getStatusLine().getStatusCode()
== HttpStatus.SC_NOT_FOUND) {
String errMsg =
"Failed to send : HTTP error code : "
+ response.getStatusLine().getStatusCode();
s_logger.error(errMsg);
String unsupportMsg =
"Unsupported command "
+ agentUri.getPath()
+ ". Are you sure you got the right type of"
+ " server?";
Answer ans = new UnsupportedAnswer(null, unsupportMsg);
s_logger.error(ans);
result = s_gson.toJson(new Answer[] {ans});
} else if (response.getStatusLine().getStatusCode()
!= HttpStatus.SC_OK) {
String errMsg =
"Failed send to " + agentUri.toString()
+ " : HTTP error code : "
+ response.getStatusLine().getStatusCode();
s_logger.error(errMsg);
return null;
} else {
result = EntityUtils.toString(response.getEntity());
s_logger.debug("POST response is" + result);
}
} catch (ClientProtocolException protocolEx) {
// Problem with HTTP message exchange
s_logger.error(protocolEx);
} catch (IOException connEx) {
// Problem with underlying communications
s_logger.error(connEx);
} finally {
httpClient.getConnectionManager().shutdown();
}
return result;
}
@Override
protected final String getDefaultScriptsDir() {
// TODO Auto-generated method stub
return null;
}
// NB: 'params' can come from one of two places.
// For a new host, HypervServerDiscoverer.find().
// For an existing host, DiscovererBase.reloadResource().
// In the later case, the params Map is populated with predefined keys
// and custom keys from the database that were passed out by the find()
// call.
// the custom keys go by the variable name 'details'.
// Thus, in find(), you see that 'details' are added to the params Map.
@Override
public final boolean configure(final String name,
final Map<String, Object> params) throws ConfigurationException {
/* todo: update, make consistent with the xen server equivalent. */
_guid = (String) params.get("guid");
_zoneId = (String) params.get("zone");
_podId = (String) params.get("pod");
_clusterId = (String) params.get("cluster");
_agentIp = (String) params.get("ipaddress"); // was agentIp
_name = name;
_clusterGuid = (String) params.get("cluster.guid");
_username = (String) params.get("url");
_password = (String) params.get("password");
_username = (String) params.get("username");
_configureCalled = true;
return true;
}
@Override
public void setName(final String name) {
// TODO Auto-generated method stub
}
@Override
public void setConfigParams(final Map<String, Object> params) {
// TODO Auto-generated method stub
}
@Override
public final Map<String, Object> getConfigParams() {
// TODO Auto-generated method stub
return null;
}
@Override
public final int getRunLevel() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void setRunLevel(final int level) {
// TODO Auto-generated method stub
}
}

View File

@ -0,0 +1,938 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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.
package com.cloud.hypervisor.hyperv.test;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.naming.ConfigurationException;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.google.gson.Gson;
import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.CreateStoragePoolCommand;
import com.cloud.agent.api.DeleteStoragePoolCommand;
import com.cloud.agent.api.GetHostStatsAnswer;
import com.cloud.agent.api.GetHostStatsCommand;
import com.cloud.agent.api.GetStorageStatsAnswer;
import com.cloud.agent.api.GetStorageStatsCommand;
import com.cloud.agent.api.GetVmStatsAnswer;
import com.cloud.agent.api.GetVmStatsCommand;
import com.cloud.agent.api.ModifyStoragePoolCommand;
import com.cloud.agent.api.StartAnswer;
import com.cloud.agent.api.StartCommand;
import com.cloud.agent.api.StartupCommand;
import com.cloud.agent.api.StartupRoutingCommand;
import com.cloud.agent.api.StartupRoutingCommand.VmState;
import com.cloud.agent.api.StartupStorageCommand;
import com.cloud.agent.api.StopAnswer;
import com.cloud.agent.api.StopCommand;
import com.cloud.agent.api.storage.CreateAnswer;
import com.cloud.agent.api.storage.CreateCommand;
import com.cloud.agent.api.storage.DestroyCommand;
import com.cloud.agent.api.storage.PrimaryStorageDownloadAnswer;
import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand;
import com.cloud.hypervisor.Hypervisor;
import com.cloud.hypervisor.hyperv.resource.HypervDirectConnectResource;
import com.cloud.network.Networks.RouterPrivateIpStrategy;
import com.cloud.serializer.GsonHelper;
import com.cloud.storage.Storage;
import com.cloud.storage.Storage.StoragePoolType;
import com.cloud.utils.PropertiesUtil;
import com.cloud.utils.exception.CloudRuntimeException;
/**
* Functional test suit for Hyper-V plugin.
*
* mvn clean build -DskipTests=false
**/
public class HypervDirectConnectResourceTest {
private static final Logger s_logger = Logger
.getLogger(HypervDirectConnectResourceTest.class.getName());
// TODO: make this a config parameter
private static final String sampleLegitDiskImageURL = "http://s3-eu-west-1.amazonaws.com/cshv3eu/SmallDisk.vhdx";
private static final Gson s_gson = GsonHelper.getGson();
private static final HypervDirectConnectResource s_hypervresource =
new HypervDirectConnectResource();
private static String s_testLocalStoreUUID =
"5fe2bad3-d785-394e-9949-89786b8a63d2";
private static String s_testLocalStorePath = "." + File.separator
+ "var" + File.separator + "test" + File.separator + "storagepool";
private static String s_testSecondaryStoreLocalPath = "."
+ File.separator
+ "var" + File.separator + "test" + File.separator + "secondary";
// TODO: differentiate between NFS and HTTP template URLs.
private static String s_testSampleTemplateUUID =
"TestCopiedLocalTemplate.vhdx";
private static String s_testSampleTemplateURL = s_testSampleTemplateUUID;
// test volumes are both a minimal size vhdx. Changing the extension to .vhd
// makes on corrupt.
private static String s_testSampleVolumeWorkingUUID =
"TestVolumeLegit.vhdx";
private static String s_testSampleVolumeWorkingUUIDNoExt =
"TestVolumeLegit";
private static String s_testSampleVolumeCorruptUUID =
"TestVolumeCorrupt.vhd";
private static String s_testSampleVolumeTempUUID =
"TestVolumeTemp.vhdx";
private static String s_testSampleVolumeWorkingURIJSON;
private static String s_testSampleVolumeCorruptURIJSON;
private static String s_testSampleVolumeTempURIJSON;
private static String s_testSampleTemplateURLJSON;
private static String s_testLocalStorePathJSON;
private static String s_agentExecutable;
private static Process s_agentProc;
private static String s_testPrimaryDataStoreHost;
public HypervDirectConnectResourceTest() {
}
/**
* Prep test environment.
**/
@Before
public final void setUp() throws ConfigurationException {
// Obtain script locations from agent.properties
final Map<String, Object> params =
PropertiesUtil.toMap(loadProperties());
// Used to create existing StoragePool in preparation for the
// ModifyStoragePool
params.put("local.storage.uuid", s_testLocalStoreUUID);
// Make sure secondary store is available.
File testSecondarStoreDir = new File(s_testSecondaryStoreLocalPath);
if (!testSecondarStoreDir.exists()) {
testSecondarStoreDir.mkdirs();
}
Assert.assertTrue("Need to be able to create the folder "
+ s_testSecondaryStoreLocalPath,
testSecondarStoreDir.exists());
try {
params.put("local.secondary.storage.path",
testSecondarStoreDir.getCanonicalPath());
} catch (IOException e1) {
// TODO Auto-generated catch block
Assert.fail("No canonical path for "
+ testSecondarStoreDir.getAbsolutePath());
}
// Clean up old test files in local storage folder:
File testPoolDir = new File(s_testLocalStorePath);
if (!testPoolDir.exists()) {
testPoolDir.mkdirs();
}
Assert.assertTrue(
"To simulate local file system Storage Pool, "
+ " you need folder at "
+ testPoolDir.getPath(), testPoolDir.exists()
&& testPoolDir.isDirectory());
try {
s_testLocalStorePath = testPoolDir.getCanonicalPath();
} catch (IOException e) {
Assert.fail("No canonical path for "
+ testPoolDir.getAbsolutePath());
}
params.put("local.storage.path", s_testLocalStorePath);
File testVolWorks =
new File(s_testLocalStorePath + File.separator
+ s_testSampleVolumeWorkingUUID);
if (!testVolWorks.exists()) {
ReadableByteChannel rbc;
try {
URL sampleLegitDiskImageURL = new URL("http://s3-eu-west-1.amazonaws.com/cshv3eu/SmallDisk.vhdx");
rbc = Channels.newChannel(sampleLegitDiskImageURL.openStream());
FileOutputStream fos = new FileOutputStream(testVolWorks);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Assert.assertTrue(
"Need to put a sample working virtual disk at "
+ testVolWorks.getPath(), testVolWorks.exists());
try {
s_testSampleVolumeWorkingURIJSON =
s_gson.toJson(testVolWorks.getCanonicalPath());
} catch (IOException e) {
Assert.fail("No canonical path for "
+ testPoolDir.getAbsolutePath());
}
FilenameFilter vhdsFilt = new FilenameFilter() {
@Override
public boolean accept(final File directory, final String fileName) {
return fileName.endsWith(".vhdx") || fileName.endsWith(".vhd");
}
};
for (File file : testPoolDir.listFiles(vhdsFilt)) {
if (file.getName().equals(testVolWorks.getName())) {
continue;
}
Assert.assertTrue("Should have deleted file " + file.getPath(),
file.delete());
s_logger.info("Cleaned up by delete file " + file.getPath());
}
s_testSampleVolumeTempURIJSON =
createTestDiskImageFromExistingImage(testVolWorks,
s_testLocalStorePath, s_testSampleVolumeTempUUID);
s_logger.info("Created " + s_testSampleVolumeTempURIJSON);
s_testSampleVolumeCorruptURIJSON =
createTestDiskImageFromExistingImage(testVolWorks,
s_testLocalStorePath, s_testSampleVolumeCorruptUUID);
s_logger.info("Created " + s_testSampleVolumeCorruptURIJSON);
createTestDiskImageFromExistingImage(testVolWorks,
s_testLocalStorePath,
s_testSampleTemplateUUID);
s_testSampleTemplateURLJSON = s_testSampleTemplateUUID;
s_logger.info("Created " + s_testSampleTemplateURLJSON
+ " in local storage.");
// Create secondary storage template:
createTestDiskImageFromExistingImage(testVolWorks,
testSecondarStoreDir.getAbsolutePath(),
"af39aa7f-2b12-37e1-86d3-e23f2f005101.vhdx");
s_logger.info("Created " + "af39aa7f-2b12-37e1-86d3-e23f2f005101.vhdx"
+ " in secondary (NFS) storage.");
s_testLocalStorePathJSON = s_gson.toJson(s_testLocalStorePath);
String agentIp = (String) params.get("ipaddress");
s_logger.info("Test using agent IP address " + agentIp);
params.put("agentIp", agentIp);
setTestJsonResult(params);
s_hypervresource.configure("hypervresource", params);
// Verify sample template is in place storage pool
s_logger.info("setUp complete, sample StoragePool at "
+ s_testLocalStorePathJSON
+ " sample template at " + s_testSampleTemplateURLJSON);
s_agentExecutable = (String) params.get("agent.executable");
s_testPrimaryDataStoreHost = (String) params.get("ipaddress");
agentCreation();
}
private String createTestDiskImageFromExistingImage(final File srcFile,
final String dstPath,
final String dstFileName) {
String newFileURIJSON = null;
File testVolTemp = new File(dstPath + File.separator + dstFileName);
try {
Files.copy(srcFile.toPath(), testVolTemp.toPath());
} catch (IOException e) {
; // NOP
}
Assert.assertTrue(
"Should be a temporary file created from the valid volume) at "
+ testVolTemp.getPath(), testVolTemp.exists());
try {
newFileURIJSON = s_gson.toJson(testVolTemp.getCanonicalPath());
} catch (IOException e) {
Assert.fail("No file at " + testVolTemp.getAbsolutePath());
}
return newFileURIJSON;
}
@Test
public final void testGetVmStatsCommand() {
// Sample GetVmStatsCommand
List<String> vmNames = new ArrayList<String>();
vmNames.add("i-2-11-VM");
GetVmStatsCommand cmd =
new GetVmStatsCommand(vmNames, "1", "localhost");
s_hypervresource.executeRequest(cmd);
GetVmStatsAnswer ans =
(GetVmStatsAnswer) s_hypervresource.executeRequest(cmd);
Assert.assertTrue(ans.getDetails(), ans.getResult());
}
public final void testStartupCommand() {
StartupRoutingCommand defaultStartRoutCmd = new StartupRoutingCommand(
0, 0, 0, 0, null, Hypervisor.HypervisorType.Hyperv,
RouterPrivateIpStrategy.HostLocal,
new HashMap<String, VmState>());
// Identity within the data centre is decided by CloudStack kernel,
// and passed via ServerResource.configure()
defaultStartRoutCmd.setDataCenter("1");
defaultStartRoutCmd.setPod("1");
defaultStartRoutCmd.setCluster("1");
defaultStartRoutCmd.setGuid("1");
defaultStartRoutCmd.setName("1");
defaultStartRoutCmd.setPrivateIpAddress("1");
defaultStartRoutCmd.setStorageIpAddress("1");
defaultStartRoutCmd.setCpus(12);
// TODO: does version need to be hard coded.
defaultStartRoutCmd.setVersion("4.2.0");
StartupCommand scmd = defaultStartRoutCmd;
Command[] cmds = {scmd};
String cmdsStr = s_gson.toJson(cmds);
s_logger.debug("Commands[] toJson is " + cmdsStr);
Command[] result = s_gson.fromJson(cmdsStr, Command[].class);
s_logger.debug("Commands[] fromJson is " + s_gson.toJson(result));
s_logger.debug("Commands[] first element has type"
+ result[0].toString());
}
// @Test
public final void testJson() {
StartupStorageCommand sscmd = null;
com.cloud.agent.api.StoragePoolInfo pi =
new com.cloud.agent.api.StoragePoolInfo(
"test123", "192.168.0.1", "c:\\", "c:\\",
StoragePoolType.Filesystem, 100L, 50L);
sscmd = new StartupStorageCommand();
sscmd.setPoolInfo(pi);
sscmd.setGuid(pi.getUuid());
sscmd.setDataCenter("foo");
sscmd.setResourceType(Storage.StorageResourceType.STORAGE_POOL);
s_logger.debug("StartupStorageCommand fromJson is "
+ s_gson.toJson(sscmd));
}
@Test
public final void testBadGetVmStatsCommand() {
// Sample GetVmStatsCommand
List<String> vmNames = new ArrayList<String>();
vmNames.add("FakeVM");
GetVmStatsCommand vmStatsCmd =
new GetVmStatsCommand(vmNames, "1", "localhost");
GetVmStatsAnswer ans =
(GetVmStatsAnswer) s_hypervresource.executeRequest(vmStatsCmd);
Assert.assertTrue(ans.getDetails(), ans.getResult());
}
@Test
public final void testCreateStoragePoolCommand() {
String folderName = "." + File.separator + "Dummy";
StoragePoolVO pool = createTestStoragePoolVO(folderName);
CreateStoragePoolCommand cmd = new CreateStoragePoolCommand(true, pool);
s_logger.debug("TestCreateStoragePoolCommand sending "
+ s_gson.toJson(cmd));
Answer ans = s_hypervresource.executeRequest(cmd);
Assert.assertTrue(ans.getResult());
}
@Test
public final void testModifyStoragePoolCommand() {
// Create dummy folder
String folderName = "." + File.separator + "Dummy";
StoragePoolVO pool = createTestStoragePoolVO(folderName);
ModifyStoragePoolCommand cmd = new ModifyStoragePoolCommand(
true, pool, folderName);
Answer ans = s_hypervresource.executeRequest(cmd);
Assert.assertTrue(ans.getResult());
DeleteStoragePoolCommand delCmd =
new DeleteStoragePoolCommand(pool, folderName);
Answer ans2 = s_hypervresource.executeRequest(delCmd);
Assert.assertTrue(ans2.getResult());
}
// Check
@Test
public final void testModifyStoragePoolCommand2() {
// Should return existing pool
// Create dummy folder
String folderName = "." + File.separator + "Dummy";
File folder = new File(folderName);
if (!folder.exists()) {
if (!folder.mkdir()) {
Assert.assertTrue(false);
}
}
// Use same spec for pool
s_logger.info("Createing pool at : " + folderName);
StoragePoolVO pool = new StoragePoolVO(StoragePoolType.Filesystem,
"127.0.0.1", -1, folderName);
pool.setUuid(s_testLocalStoreUUID);
ModifyStoragePoolCommand cmd = new ModifyStoragePoolCommand(
true, pool, folderName);
Answer ans = s_hypervresource.executeRequest(cmd);
Assert.assertTrue(ans.getResult());
DeleteStoragePoolCommand delCmd =
new DeleteStoragePoolCommand(pool, folderName);
Answer ans2 = s_hypervresource.executeRequest(delCmd);
Assert.assertTrue(ans2.getResult());
}
public final StoragePoolVO createTestStoragePoolVO(
final String folderName) {
File folder = new File(folderName);
if (!folder.exists()) {
if (!folder.mkdir()) {
Assert.assertTrue(false);
}
}
// Use same spec for pool
s_logger.info("Createing pool at : " + folderName);
StoragePoolVO pool = new StoragePoolVO(StoragePoolType.Filesystem,
"127.0.0.1", -1, folderName);
return pool;
}
@Test
public final void testInitialize() {
StartupCommand[] startCmds = s_hypervresource.initialize();
Command[] cmds = new Command[] {startCmds[0], startCmds[1]};
String result = s_gson.toJson(cmds);
if (result == null) {
result = "NULL";
}
s_logger.debug("TestInitialize returned " + result);
s_logger.debug("TestInitialize expected " + _setTestJsonResultStr);
Assert.assertTrue("StartupCommand[] not what we expected",
_setTestJsonResultStr.equals(result));
return;
}
@Test
public final void testPrimaryStorageDownloadCommandHTTP() {
PrimaryStorageDownloadCommand cmd = samplePrimaryDownloadCommand();
cmd.setUrl("http://s3-eu-west-1.amazonaws.com/cshv3eu/SmallDisk.vhdx");
corePrimaryStorageDownloadCommandTestCycle(cmd);
}
private void corePrimaryStorageDownloadCommandTestCycle(
final PrimaryStorageDownloadCommand cmd) {
PrimaryStorageDownloadAnswer ans =
(PrimaryStorageDownloadAnswer) s_hypervresource
.executeRequest(cmd);
if (!ans.getResult()) {
s_logger.error(ans.getDetails());
} else {
s_logger.debug(ans.getDetails());
}
Assert.assertTrue(ans.getDetails(), ans.getResult());
// Test that returned URL works.
// CreateCommand createCmd = CreateCommandSample();
// CreateCommand testCreateCmd = new
// CreateCommand(createCmd.getDiskCharacteristics(),
// ans.getInstallPath(), createCmd.getPool());
// CreateAnswer ans2 =
// (CreateAnswer)s_hypervresource.executeRequest(testCreateCmd);
// Assert.assertTrue(ans2.getDetails(), ans2.getResult());
}
private PrimaryStorageDownloadCommand samplePrimaryDownloadCommand() {
String cmdJson =
"{\"localPath\":"
+ s_testLocalStorePathJSON
+ ",\"poolUuid\":\""
+ s_testLocalStoreUUID
+ "\",\"poolId\":201,"
+ "\"secondaryStorageUrl\":"
+ "\"nfs://10.70.176.36/mnt/cshv3/secondarystorage\","
+ "\"primaryStorageUrl\":"
+ "\"nfs://10.70.176.29E:\\\\Disks\\\\Disks\","
+ "\"url\":"
+ "\"nfs://10.70.176.36/mnt/cshv3/secondarystorage/template/tmpl//2/204//af39aa7f-2b12-37e1-86d3-e23f2f005101.vhdx\","
+ "\"format\":\"VHDX\",\"accountId\":2,"
+ "\"name\":"
+ "\"204-2-5a1db1ac-932b-3e7e-a0e8-5684c72cb862\""
+ ",\"contextMap\":{},\"wait\":10800}";
PrimaryStorageDownloadCommand cmd = s_gson.fromJson(cmdJson,
PrimaryStorageDownloadCommand.class);
return cmd;
}
public final CreateCommand createCommandSample() {
String sample =
"{\"volId\":17,\"pool\":{\"id\":201,\"uuid\":\""
+ s_testLocalStoreUUID
+ "\",\"host\":\"10.70.176.29\""
+ ",\"path\":"
+ s_testLocalStorePathJSON
+ ",\"port\":0,\"type\":\"Filesystem\"},"
+ "\"diskCharacteristics\":{\"size\":0,"
+ "\"tags\":[],\"type\":\"ROOT\",\"name\":\"ROOT-15\","
+ "\"useLocalStorage\":true,\"recreatable\":true,"
+ "\"diskOfferingId\":11,"
+ "\"volumeId\":17,\"hyperType\":\"Hyperv\"},"
+ "\"templateUrl\":"
+ s_testSampleTemplateURLJSON + ",\"wait\":0}";
CreateCommand cmd = s_gson.fromJson(sample, CreateCommand.class);
return cmd;
}
@Test
public final void testCreateCommand() {
String sample =
"{\"volId\":10,\"pool\":{\"id\":201,\"uuid\":\""
+ s_testLocalStoreUUID
+ "\",\"host\":\"10.70.176.29\""
+ ",\"path\":"
+ s_testLocalStorePathJSON
+ ",\"port\":0,\"type\":\"Filesystem\"},"
+ "\"diskCharacteristics\":{\"size\":0,"
+ "\"tags\":[],\"type\":\"ROOT\",\"name\":\"ROOT-9\","
+ "\"useLocalStorage\":true,\"recreatable\":true,"
+ "\"diskOfferingId\":11,"
+ "\"volumeId\":10,\"hyperType\":\"Hyperv\"},"
+ "\"templateUrl\":"
+ s_testSampleTemplateURLJSON
+ ",\"contextMap\":{},\"wait\":0}";
File destDir = new File(s_testLocalStorePath);
Assert.assertTrue(destDir.isDirectory());
File testSampleTemplateURLFile =
new File(s_testLocalStorePath
+ File.separator
+ s_gson.fromJson(s_testSampleTemplateURLJSON,
String.class));
Assert.assertTrue(
"The template that create should make"
+ " volumes from is missing from path "
+ testSampleTemplateURLFile.getPath(),
testSampleTemplateURLFile.exists());
int fileCount = destDir.listFiles().length;
s_logger.debug(" test local store has " + fileCount + "files");
// Test requires there to be a template at the tempalteUrl, which is its
// location in the local file system.
CreateCommand cmd = s_gson.fromJson(sample, CreateCommand.class);
CreateAnswer ans = (CreateAnswer) s_hypervresource.executeRequest(cmd);
Assert.assertTrue(ans.getDetails(), ans.getResult());
Assert.assertTrue("CreateCommand should add a file to the folder",
fileCount + 1 == destDir.listFiles().length);
File newFile = new File(ans.getVolume().getPath());
Assert.assertTrue("The new file should have a size greater than zero",
newFile.length() > 0);
newFile.delete();
}
@Test
public final void testStartCommandCorruptDiskImage() {
String sampleStart =
"{\"vm\":{\"id\":16,\"name\":\"i-3-17-VM\","
+ "\"type\":\"User\",\"cpus\":1,\"speed\":500,"
+ "\"minRam\":536870912,\"maxRam\":536870912,"
+ "\"arch\":\"x86_64\","
+ "\"os\":\"CentOS 6.0 (64-bit)\","
+ "\"bootArgs\":\"\",\"rebootOnCrash\":false,"
+ "\"enableHA\":false,"
+ "\"limitCpuUse\":false,"
+ "\"vncPassword\":\"31f82f29aff646eb\","
+ "\"params\":{},"
+ "\"uuid\":\"8b030b6a-0243-440a-8cc5-45d08815ca11\""
+ ",\"disks\":["
+ "{\"id\":18,\"name\":\""
+ s_testSampleVolumeCorruptUUID
+ "\","
+ "\"mountPoint\":"
+ s_testSampleVolumeCorruptURIJSON
+ ","
+ "\"path\":"
+ s_testSampleVolumeCorruptURIJSON
+ ",\"size\":0,"
+ "\"type\":\"ROOT\","
+ "\"storagePoolType\":\"Filesystem\","
+ "\"storagePoolUuid\":\""
+ s_testLocalStoreUUID
+ "\""
+ ",\"deviceId\":0},"
+ "{\"id\":16,\"name\":\"Hyper-V Sample2\",\"size\":0,"
+ "\"type\":\"ISO\",\"storagePoolType\":\"ISO\","
+ "\"deviceId\":3}],"
+ "\"nics\":["
+ "{\"deviceId\":0,\"networkRateMbps\":100,"
+ "\"defaultNic\":true,"
+ "\"uuid\":\"99cb4813-23af-428c-a87a-2d1899be4f4b\","
+ "\"ip\":\"10.1.1.67\",\"netmask\":\"255.255.255.0\","
+ "\"gateway\":\"10.1.1.1\","
+ "\"mac\":\"02:00:51:2c:00:0e\",\"dns1\":\"4.4.4.4\","
+ "\"broadcastType\":\"Vlan\",\"type\":\"Guest\","
+ "\"broadcastUri\":\"vlan://261\","
+ "\"isolationUri\":\"vlan://261\","
+ "\"isSecurityGroupEnabled\":false}"
+ "]},\"contextMap\":{},\"wait\":0}";
StartCommand cmd = s_gson.fromJson(sampleStart, StartCommand.class);
StartAnswer ans =
(StartAnswer) s_hypervresource.executeRequest(cmd);
Assert.assertFalse(ans.getDetails(), ans.getResult());
}
@Test
public final void testStartStopCommand() {
String sample = getSampleStartCommand();
StartAnswer sans = simpleVmStart(sample);
Assert.assertTrue(sans.getDetails(), sans.getResult());
StopAnswer stopAns = simpleVmStop();
Assert.assertTrue(stopAns.getDetails(), stopAns.getResult());
}
@Test
public final void testStartStartCommand() {
String sample = getSampleStartCommand();
StartAnswer sans = simpleVmStart(sample);
Assert.assertTrue(sans.getDetails(), sans.getResult());
simpleVmStart(sample);
StopAnswer ans = simpleVmStop();
Assert.assertTrue(ans.getDetails(), ans.getResult());
}
private StopAnswer simpleVmStop() {
String sampleStop =
"{\"isProxy\":false,\"vmName\":\"i-2-17-VM\","
+ "\"contextMap\":{},\"wait\":0}";
StopCommand cmd = s_gson.fromJson(sampleStop, StopCommand.class);
StopAnswer ans = (StopAnswer) s_hypervresource.executeRequest(cmd);
return ans;
}
private StartAnswer simpleVmStart(final String sample) {
StartCommand cmd = s_gson.fromJson(sample, StartCommand.class);
s_logger.info("StartCommand sample " + s_gson.toJson(cmd));
StartAnswer ans =
(StartAnswer) s_hypervresource.executeRequest(cmd);
return ans;
}
@Test
public final void testDestroyCommand() {
// TODO: how does the command vary when we are only deleting a vm versus
// deleting a volume?
// String sample2 = "{\"volume\":" + getSampleVolumeObjectTO() + "}";
String sample2 =
"{\"volume\":{\"name\":\"" + s_testSampleVolumeWorkingUUIDNoExt
+ "\",\"storagePoolType\":\"Filesystem\","
+ "\"mountPoint\":"
+ s_testLocalStorePathJSON
+ ",\"path\":" + s_testSampleVolumeTempURIJSON
+ ",\"storagePoolUuid\":\"" + s_testLocalStoreUUID
+ "\","
+ "\"type\":\"ROOT\",\"id\":9,\"size\":0}}";
DestroyCommand cmd = s_gson.fromJson(sample2, DestroyCommand.class);
Answer ans = (Answer) s_hypervresource.executeRequest(cmd);
Assert.assertTrue(ans.getDetails(), ans.getResult());
}
@Test
public final void testGetStorageStatsCommand() {
// TODO: Update sample data to unsure it is using correct info.
String sample =
"{\"id\":\""
+ s_testLocalStoreUUID
+ "\",\"localPath\":"
+ s_testLocalStorePathJSON
+ ","
+ "\"pooltype\":\"Filesystem\","
+ "\"contextMap\":{},\"wait\":0}";
s_logger.info("Sample JSON: " + sample);
GetStorageStatsCommand cmd =
s_gson.fromJson(sample, GetStorageStatsCommand.class);
s_hypervresource.executeRequest(cmd);
GetStorageStatsAnswer ans =
(GetStorageStatsAnswer) s_hypervresource.executeRequest(cmd);
Assert.assertTrue(ans.getDetails(), ans.getResult());
Assert.assertTrue(ans.getByteUsed() != ans.getCapacityBytes());
}
@After
public final void agentTerminate() {
// Write carriage return line feed to script's stdin
OutputStream scriptInput = s_agentProc.getOutputStream();
OutputStreamWriter siw = new OutputStreamWriter(scriptInput);
try {
BufferedWriter writer = new BufferedWriter(siw);
writer.write("\r\n");
writer.flush();
writer.close();
} catch (IOException ex) {
s_logger.debug("Error closing agent at " + s_agentExecutable
+ " message " + ex.getMessage());
}
}
private void agentCreation() {
// Launch script
try {
List<String> exeArgs = new ArrayList<String>();
exeArgs.add(s_agentExecutable);
exeArgs.add("--console");
// when we launch from the shell, we need to use Cygwin's path to
// the exe
ProcessBuilder builder = new ProcessBuilder(exeArgs);
builder.redirectErrorStream(true);
s_agentProc = builder.start();
Thread.sleep(4000);
} catch (Exception ex) {
s_logger.debug("Error calling starting aget at "
+ s_agentExecutable
+ " message " + ex.getMessage());
}
}
@Test
public final void testGetHostStatsCommand() {
// Arrange
long hostIdVal = 123;
GetHostStatsCommand cmd = new GetHostStatsCommand("1", "testHost",
hostIdVal);
// Act
GetHostStatsAnswer ans = (GetHostStatsAnswer) s_hypervresource
.executeRequest(cmd);
// Assert
Assert.assertTrue(ans.getResult());
Assert.assertTrue(0.0 < ans.getTotalMemoryKBs());
Assert.assertTrue(0.0 < ans.getFreeMemoryKBs());
Assert.assertTrue(0.0 <= ans.getNetworkReadKBs());
Assert.assertTrue(0.0 <= ans.getNetworkWriteKBs());
Assert.assertTrue(0.0 <= ans.getCpuUtilization());
Assert.assertTrue(100 >= ans.getCpuUtilization());
Assert.assertTrue(ans.getEntityType().equals("host"));
Assert.assertTrue(ans.getDetails() == null);
}
public static Properties loadProperties() throws ConfigurationException {
Properties properties = new Properties();
final File file = PropertiesUtil.findConfigFile("agent.properties");
if (file == null) {
throw new ConfigurationException(
"Unable to find agent.properties.");
}
s_logger.info("agent.properties found at " + file.getAbsolutePath());
try {
properties.load(new FileInputStream(file));
} catch (final FileNotFoundException ex) {
throw new CloudRuntimeException("Cannot find the file: "
+ file.getAbsolutePath(), ex);
} catch (final IOException ex) {
throw new CloudRuntimeException("IOException in reading "
+ file.getAbsolutePath(), ex);
}
return properties;
}
private String _setTestJsonResultStr = null;
public final void setTestJsonResult(final Map<String, Object> params) {
File dir = new File((String) params.get("DefaultVirtualDiskFolder"));
long usableCapacity = dir.getUsableSpace() - 4294967296L;
long totalSpace = dir.getTotalSpace() - 4294967296L;
// TODO: add test to verify capacity statistics change
_setTestJsonResultStr =
String.format(
"[{\"com.cloud.agent.api.StartupRoutingCommand\":{"
+ "\"cpus\":%s,"
+ "\"speed\":%s,"
+ "\"memory\":%s,"
+ "\"dom0MinMemory\":%s,"
+ "\"poolSync\":false,"
+ "\"vms\":{},"
+ "\"caps\":\"hvm\","
+ "\"hypervisorType\":\"Hyperv\","
+ "\"hostDetails\":{"
+ "\"com.cloud.network.Networks.RouterPrivateIpStrategy\":"
+ "\"HostLocal\""
+ "},"
+ "\"type\":\"Routing\","
+ "\"dataCenter\":%s,"
+ "\"pod\":%s,"
+ "\"cluster\":%s,"
+ "\"guid\":\"16f85622-4508-415e-b13a-49a39bb14e4d\","
+ "\"name\":\"hypervresource\","
+ "\"version\":\"4.2.0\","
+ "\"privateIpAddress\":%s,"
+ "\"privateMacAddress\":%s,"
+ "\"privateNetmask\":%s,"
+ "\"storageIpAddress\":%s,"
+ "\"storageNetmask\":%s,"
+ "\"storageMacAddress\":%s,"
+ "\"gatewayIpAddress\":%s,"
+ "\"contextMap\":{},"
+ "\"wait\":0"
+ "}},"
+ "{\"com.cloud.agent.api.StartupStorageCommand\":{"
+ "\"totalSize\":0,"
+ "\"poolInfo\":{"
+ "\"uuid\":\"16f85622-4508-415e-b13a-49a39bb14e4d\","
+ "\"host\":%s,"
+ "\"localPath\":%s,"
+ "\"hostPath\":%s,"
+ "\"poolType\":\"Filesystem\","
+ "\"capacityBytes\":%s,"
+ "\"availableBytes\":%s"
+ "},"
+ "\"resourceType\":\"STORAGE_POOL\","
+ "\"hostDetails\":{},"
+ "\"type\":\"Storage\","
+ "\"dataCenter\":\"1\","
+ "\"guid\":"
+ "\"16f85622-4508-415e-b13a-49a39bb14e4d\","
+ "\"contextMap\":{},"
+ "\"wait\":0"
+ "}}]",
params.get("TestCoreCount"),
params.get("TestCoreMhz"),
params.get("TestMemoryMb"),
params.get("TestDom0MinMemoryMb"),
s_gson.toJson((String) params.get("zone")),
s_gson.toJson((String) params.get("pod")),
s_gson.toJson((String) params.get("cluster")),
s_gson.toJson((String) params.get("ipaddress")),
s_gson.toJson((String) params
.get("private.mac.address")),
s_gson.toJson((String) params.get(
"private.ip.netmask")),
s_gson.toJson((String) params.get("ipaddress")),
s_gson.toJson((String) params.get(
"private.ip.netmask")),
s_gson.toJson((String) params
.get("private.mac.address")),
s_gson.toJson((String) params.get(
"gateway.ip.address")),
s_gson.toJson((String) params.get("ipaddress")),
s_gson.toJson((String) params
.get("DefaultVirtualDiskFolder")),
s_gson.toJson((String) params
.get("DefaultVirtualDiskFolder")),
s_gson.toJson(totalSpace),
s_gson.toJson(usableCapacity)
);
}
public static String getSamplePrimaryDataStoreInfo() {
String samplePrimaryDataStoreInfo =
"{\"org.apache.cloudstack.storage.to.PrimaryDataStoreTO\":"
+ "{\"uuid\":\"" + s_testLocalStoreUUID + "\","
+ "\"id\":201,"
+ "\"host\":\"" + s_testPrimaryDataStoreHost + "\","
+ "\"type\":\"Filesystem\"," // Not used in
// PrimaryDataStoreTO
+ "\"poolType\":\"Filesystem\"," // Not used in
// PrimaryDataStoreTO
+ "\"path\":" + s_testLocalStorePathJSON + ","
+ "\"port\":0}"
+ "}";
return samplePrimaryDataStoreInfo;
}
public static String getSampleVolumeObjectTO() {
String sampleVolumeObjectTO =
"{\"org.apache.cloudstack.storage.to.VolumeObjectTO\":"
+ "{\"uuid\":\"19ae8e67-cb2c-4ab4-901e-e0b864272b59\","
+ "\"volumeType\":\"ROOT\","
+ "\"format\":\"VHDX\","
+ "\"dataStore\":" + getSamplePrimaryDataStoreInfo()
+ ","
+ "\"name\":\"" + s_testSampleVolumeWorkingUUIDNoExt + "\","
+ "\"size\":52428800,"
+ "\"volumeId\":10,"
// "\"vmName\":\"i-3-5-VM\"," + // TODO: required?
+ "\"accountId\":3,\"id\":10}"
+ "}"; // end of destTO
return sampleVolumeObjectTO;
}
public static String getSampleStartCommand() {
String sample =
"{\"vm\":{\"id\":17,\"name\":\"i-2-17-VM\","
+ "\"type\":\"User\",\"cpus\":1,\"speed\":500,"
+ "\"minRam\":536870912,\"maxRam\":536870912,"
+ "\"arch\":\"x86_64\","
+ "\"os\":\"CentOS 6.0 (64-bit)\","
+ "\"bootArgs\":\"\",\"rebootOnCrash\":false,"
+ "\"enableHA\":false,\"limitCpuUse\":false,"
+ "\"vncPassword\":\"31f82f29aff646eb\","
+ "\"params\":{},"
+ "\"uuid\":\"8b030b6a-0243-440a-8cc5-45d08815ca11\""
+ ",\"disks\":["
+ "{\"data\":"
+ getSampleVolumeObjectTO()
+ ",\"diskSeq\":0,\"type\":\"ROOT\"},"
+ "{\"diskSeq\":1,\"type\":\"ISO\"}"
+ "],"
+ "\"nics\":["
+ "{\"deviceId\":0,\"networkRateMbps\":100,"
+ "\"defaultNic\":true,"
+ "\"uuid\":\"99cb4813-23af-428c-a87a-2d1899be4f4b\","
+ "\"ip\":\"10.1.1.67\","
+ "\"netmask\":\"255.255.255.0\","
+ "\"gateway\":\"10.1.1.1\","
+ "\"mac\":\"02:00:51:2c:00:0e\",\"dns1\":\"4.4.4.4\","
+ "\"broadcastType\":\"Vlan\",\"type\":\"Guest\","
+ "\"broadcastUri\":\"vlan://261\","
+ "\"isolationUri\":\"vlan://261\","
+ "\"isSecurityGroupEnabled\":false}"
+ "]},\"contextMap\":{},\"wait\":0}";
return sample;
}
}

View File

@ -40,6 +40,7 @@
<module>event-bus/rabbitmq</module>
<module>hypervisors/baremetal</module>
<module>hypervisors/ucs</module>
<module>hypervisors/hyperv</module>
<module>network-elements/elastic-loadbalancer</module>
<module>network-elements/ovs</module>
<module>network-elements/juniper-contrail</module>
@ -119,6 +120,17 @@
<module>hypervisors/kvm</module>
</modules>
</profile>
<profile>
<id>hyperV</id>
<activation>
<property>
<name>hyperV</name>
</property>
</activation>
<modules>
<module>hypervisors/hyperv</module>
</modules>
</profile>
<profile>
<id>f5</id>
<activation>

View File

@ -206,8 +206,8 @@ public class HighAvailabilityManagerImpl extends ManagerBase implements HighAvai
return;
}
if(host.getHypervisorType() == HypervisorType.VMware) {
s_logger.info("Don't restart for VMs on host " + host.getId() + " as the host is VMware host");
if(host.getHypervisorType() == HypervisorType.VMware || host.getHypervisorType() == HypervisorType.Hyperv) {
s_logger.info("Don't restart for VMs on host " + host.getId() + " as the host is VMware host or on Hyperv Host");
return;
}
@ -302,6 +302,11 @@ public class HighAvailabilityManagerImpl extends ManagerBase implements HighAvai
return;
}
if(vm.getHypervisorType() == HypervisorType.VMware || vm.getHypervisorType() == HypervisorType.Hyperv) {
s_logger.info("Skip HA for VMware VM or Hyperv VM" + vm.getInstanceName());
return;
}
if (!investigate) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("VM does not require investigation so I'm marking it as Stopped: " + vm.toString());

View File

@ -133,7 +133,9 @@ public class ControlNetworkGuru extends PodBasedNetworkGuru implements NetworkGu
InsufficientAddressCapacityException {
assert nic.getTrafficType() == TrafficType.Control;
if (dest.getHost().getHypervisorType() == HypervisorType.VMware && isRouterVm(vm)) {
// we have to get management/private ip for the control nic for vmware/hyperv due ssh issues.
HypervisorType hType = dest.getHost().getHypervisorType();
if ( ( (hType == HypervisorType.VMware) || (hType == HypervisorType.Hyperv) )&& isRouterVm(vm)) {
if(dest.getDataCenter().getNetworkType() != NetworkType.Basic) {
super.reserve(nic, config, vm, dest, context);