最近准备基于Microsoft Azure Management Libraries 实现虚拟机的监控。主要的需求就是获取虚拟机内置的性能计数器数据,基于性能计数器实现后续的监控和自动伸缩。

作为这一票研究的第一篇,我们以连接中国区的Azure作为起步吧。

通过Azure的订阅(Subscription)建立Azure的连接

首先要有连接的凭据,通过代码验证,这里主要有两种连接凭据:令牌凭据(TokenCloudCredentials)和证书凭据(CertificateCloudCredentials)。

我们主要介绍令牌凭据(TokenCloudCredentials):这里用到了Window Azure的OAuth认证,需要在Azure Manage Portal中允许我们的App访问Azure。

微软提供了一个入门的链接,不过貌似不是针对咱们天朝的,同时有代码编译不通过的问题,可以参考一下:

https://msdn.microsoft.com/en-us/zh-us/library/azure/dn722415.aspx

整体上分为三步:

  1. 在Azure AD(活动目录)中添加一个应用程序
  2. 创建Project添加Nuget应用
  3. 创建令牌连接Azure

我们一步一步来:

1. 在Azure AD中添加一个应用程序

访问https://manage.windowsazure.cn,输入用户名和密码登录,用户必须有Active Dictionary权限。

左边菜单倒数第二个Active Directory,选择对应的目录,点击应用程序(Applications)Tab选型卡,添加一个应用程序:AzureTestApp,类型是Native Client Application,Redirect URL设置为:http://localhost

探索Windows Azure 监控和自动伸缩系列1 - 连接中国区Azure

探索Windows Azure 监控和自动伸缩系列1 - 连接中国区Azure

探索Windows Azure 监控和自动伸缩系列1 - 连接中国区Azure

设置AzureTestApp的权限:Windows Azure Service Management API

探索Windows Azure 监控和自动伸缩系列1 - 连接中国区Azure

探索Windows Azure 监控和自动伸缩系列1 - 连接中国区Azure

探索Windows Azure 监控和自动伸缩系列1 - 连接中国区Azure

记得要保存:

探索Windows Azure 监控和自动伸缩系列1 - 连接中国区Azure

 2. 创建Project添加Nuget引用

这里使用Console工程好了,主要添加Microsoft Azure Management LibrariesActive Directory Authentication Library

Package文件是这样的:

探索Windows Azure 监控和自动伸缩系列1 - 连接中国区Azure

3. 创建令牌连接Azure

在创建令牌之前,我们需要先配置一下App.Config,将我们的订阅、应用程序信息、Login服务器、ApiEndPoint信息等,这些信息又用到了我们刚才创建的应用程序。

微软给的msdn指导说明中是这样的:我们主要用前5个:

探索Windows Azure 监控和自动伸缩系列1 - 连接中国区Azure

有个疑问,这几个key主要用在哪,后续代码中大家一看就明白了。微软给的示例说明中的URL,很明显是Azure Global的,我们需要搞成中国的URL,其中

login:https://login.chinacloudapi.cn/{0}

apiEndpoint:https://management.core.chinacloudapi.cn/

不要问我为什么,哥也是在鞠强老大的指导下,配置成这样的。

然后,ClientID、tenantID从哪找呢?subscriptionId肯定是你的订阅的ID,比如:37a8***-5107-4f9b-***-a11***0226

探索Windows Azure 监控和自动伸缩系列1 - 连接中国区Azure

探索Windows Azure 监控和自动伸缩系列1 - 连接中国区Azure

探索Windows Azure 监控和自动伸缩系列1 - 连接中国区Azure

 这样我们的App.Config就OK了,对了,还有一个redirectUri : http://localhost/

探索Windows Azure 监控和自动伸缩系列1 - 连接中国区Azure

撸代码吧:

访问App.Config肯定要添加System.configuration引用。

为了方便凭据管理,我们设计一个Azure认证器类:Authorizator

namespace AzureTest
{
    using System.Configuration;
    using Microsoft.WindowsAzure;
    using Microsoft.IdentityModel.Clients.ActiveDirectory;

    /// <summary>
    /// Window Azure登录验证器
    /// </summary>
    class Authorizator
    {
        /// <summary>
        /// 获取令牌凭据
        /// </summary>
        /// <returns>令牌凭据</returns>
        public static TokenCloudCredentials GetCredentials(string subscriptionId = "")
        {
            var token = GetAccessToken();
            if(string.IsNullOrEmpty(subscriptionId))
                subscriptionId = ConfigurationManager.AppSettings["subscriptionId"];
            var credential = new TokenCloudCredentials(subscriptionId, token);

            return credential;
        }

        /// <summary>
        /// 获取访问令牌
        /// </summary>
        /// <returns>访问令牌</returns>
        private static string GetAccessToken()
        {
            AuthenticationResult result = null;

            var context = new AuthenticationContext(string.Format(
              ConfigurationManager.AppSettings["login"],
              ConfigurationManager.AppSettings["tenantId"]));

            result = context.AcquireToken(
              ConfigurationManager.AppSettings["apiEndpoint"],
              ConfigurationManager.AppSettings["clientId"],
              new Uri(ConfigurationManager.AppSettings["redirectUri"]));

            if (result == null)
            {
                throw new InvalidOperationException("Failed to obtain the JWT token");
            }

            return result.AccessToken;
        }
   }
}

上面代码中,Azure连接认证就ok了,我们测试一下,应该弹出Azure登录验证界面:

1  static void Main(string[] args)
2         {            
3             var credential = Authorizator.GetCredentials();
4             client = new MonitorClient(credential);
5             client.GetMetricDefinitions();
6             Console.ReadLine();
7         }

探索Windows Azure 监控和自动伸缩系列1 - 连接中国区Azure

至此,Azure连接就可以了,上面代码中有些监控的代码,MonitorClient,我们将在下一篇中介绍如何获取VM的监控指标和监控数据。

 

周国庆

@济南

分类:

技术点:

相关文章: