上周有个客户提出这样的需求:根据虚拟机磁盘的实际使用量,当达到某一阈值时设置邮件提醒。
在这个需求中我们只需要解决两点问题:
- 计算虚拟机磁盘实际使用量
- 发送邮件
使用VS新建一个名为CalculatePageBlobActualUsage控制台应用程序,使用Nuget搜索“WindowsAzure.Storage”并安装
配置存储账号信息:
计算虚机磁盘实际使用量
虚机磁盘是以Page Blob文件形式存储在Storage中的,而我们付给Azure的存储费用是按实际使用量计算的,而并非是按磁盘大小计算的,那么如何知道我们虚机磁盘的实际使用量?
通过下面的代码就可以获取到使用量,只需要传入指定的PageBlob。
private static long GetActualDiskSize(CloudPageBlob pageBlob) { pageBlob.FetchAttributes(); return 124 + pageBlob.Name.Length * 2 + pageBlob.Metadata.Sum(m => m.Key.Length + m.Value.Length + 3) + pageBlob.GetPageRanges().Sum(r => 12 + (r.EndOffset - r.StartOffset)); } [DllImport("Shlwapi.dll", CharSet = CharSet.Auto)] public static extern long StrFormatByteSize(long fileSize, [MarshalAs(UnmanagedType.LPTStr)] StringBuilder buffer, int bufferSize); public static string GetFormattedDiskSize(long size) { var sb = new StringBuilder(11); StrFormatByteSize(size, sb, sb.Capacity); return sb.ToString(); }
发送邮件
关于发送邮件本身就没有任何技术难度,我们只需要做一个逻辑判断,假设我们需要当虚机磁盘使用量超过10GB就给用户发送邮件警报。
private static void SendMail(string toMailAddress, string body, string subject, string path="") { SmtpClient smtpClient = new SmtpClient("smtp.qq.com"); smtpClient.EnableSsl = true; //Credentials登陆SMTP服务器的身份验证 smtpClient.Credentials = new NetworkCredential("username", "password"); MailMessage message = new MailMessage(new MailAddress("from email"), new MailAddress(toMailAddress)); // message.Bcc.Add(new MailAddress("tst@qq.com")); //可以添加多个收件人 message.Body = body; message.Subject = subject; if (path != "") { Attachment att = new Attachment(@path); message.Attachments.Add(att); } smtpClient.Send(message); }
根据阈值发送警报邮件
private static string _storageConnectionString = ConfigurationManager.AppSettings["StorageConnectionString"]; private static string _containerName = ConfigurationManager.AppSettings["ContainerName"]; private static string _vhdName = ConfigurationManager.AppSettings["VHDName"]; static void Main(string[] args) { CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_storageConnectionString); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer blobContainer = blobClient.GetContainerReference(_containerName); CloudPageBlob pageBlob = blobContainer.GetPageBlobReference(_vhdName); long size = GetActualDiskSize(pageBlob); string actualSize = GetFormattedDiskSize(size); string toMailAddress = "huzc@nysoftland.com.cn"; string body = "您的虚机磁盘当前实际使用量为" + actualSize; string subject = "磁盘容量警报"; //阈值为10GB long threshold = (long)1024 * 1024 * 1024 * 10; if (size > threshold) { //当磁盘实际使用量大于10GB时,发送邮件警告 SendMail(toMailAddress, body, subject); } Console.ReadKey(); }
收到警报邮件
如下图所示,我们已经收到了警报邮件