├── LICENSE ├── README.md ├── config.py ├── requirement.txt ├── screenshots ├── esxi.png └── vm.png └── vsphere-monitor.py /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [2017] [freedomkk-qfeng] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## vsphere-monitor 2 | vsphere-monitor 通过 [pyvmomi](https://github.com/vmware/pyvmomi) 采集 vsphere 集群的数据。只需要连接 vcenter 就可以采集集群内的包括 ESXi,datastore,vm 等各种监控数据。数据通过 open-falcon 的数据接口上报给 open-falcon。 3 | 4 | #### 版本需求 5 | python 2.7 6 | 7 | #### 上报数据字段 8 | 9 | metric | tag | type | note 10 | -----|------|------|------ 11 | datastore.capacity|datacetner=datacenter,datastore=datastore,type=type|GAUGE| 存储容量 12 | datastore.free|datacetner=datacenter,datastore=datastore,type=type|GAUGE| 存储剩余容量 13 | datastore.freePercent|datacetner=datacenter,datastore=datastore,type=type|GAUGE| 存储剩余容量 14 | esxi.alive|datacetner=datacenter,cluster_name=cluster_name,host=host|GAUGE|esxi 存活,值为 1,可以用来做 Nodata 15 | esxi.net.if.in|datacetner=datacenter,cluster_name=cluster_name,host=host|GAUGE|esxi 网络进流量(所有网卡总和) 16 | esxi.net.if.out|datacetner=datacenter,cluster_name=cluster_name,host=host|GAUGE|esxi 网络出流量(所有网卡总和) 17 | esxi.memory.freePercent|datacetner=datacenter,cluster_name=cluster_name,host=host|GAUGE|esxi 剩余内存百分比 18 | esxi.memory.usage|datacetner=datacenter,cluster_name=cluster_name,host=host|GAUGE|esxi 内存使用量 19 | esxi.memory.capacity|datacetner=datacenter,cluster_name=cluster_name,host=host|GAUGE|esxi 内存总量 20 | esxi.cpu.usage|datacetner=datacenter,cluster_name=cluster_name,host=host|GAUGE|esxi CPU 使用率 21 | esxi.uptime|datacetner=datacenter,cluster_name=cluster_name,host=host|GAUGE|esxi uptime 22 | vm.power|vm=vm_name|GAUGE|虚机是否开机,开机 = 1,关机 = 0,可以用来做 nodata 23 | vm.net.if.in|vm=vm_name|GAUGE|虚机网络进流量(所有网卡总和) 24 | vm.net.if.out|vm=vm_name|GAUGE|虚机网络出流量(所有网卡总和) 25 | vm.datastore.io.write_latency|vm=vm_name|GAUGE|虚机存储 io 写延迟 26 | vm.datastore.io.read_latency|vm=vm_name|GAUGE|虚机存储 io 读延迟 27 | vm.datastore.io.write_numbers|vm=vm_name|GAUGE|虚机存储写 IOPS 28 | vm.datastore.io.read_numbers|vm=vm_name|GAUGE|虚机存储读 IOPS 29 | vm.datastore.io.write_bytes|vm=vm_name|GAUGE|虚机存储写流量 30 | vm.datastore.io.read_bytes|vm=vm_name|GAUGE|虚机存储读流量 31 | vm.memory.freePercent|vm=vm_name|GAUGE|虚机内存剩余百分比 32 | vm.memory.usage|vm=vm_name|GAUGE|虚机内存量使用量 33 | vm.memory.capacity|vm=vm_name|GAUGE|虚机内存量总量 34 | vm.cpu.usage|vm=vm_name|GAUGE|虚机 cpu 使用量 35 | vm.uptime|vm=vm_name|GAUGE|虚机 uptime 36 | 37 | 38 | #### 安装 39 | 获取代码 40 | ``` 41 | git clone https://github.com/freedomkk-qfeng/vsphere-monitor.git 42 | ``` 43 | 安装依赖 44 | ``` 45 | yum install -y python-virtualenv 46 | cd vsphere-monitor 47 | virtualenv ./env 48 | ./env/bin/pip install -r requirement.txt 49 | ``` 50 | #### 配置 51 | 修改配置文件 `config.py` 52 | ``` 53 | # falcon 54 | endpoint = "vcenter" # 上报给 open-falcon 的 endpoint 55 | push_api = "http://127.0.0.1:6060/api/push" # 上报的 http api 接口 56 | interval = 60 # 上报的 step 间隔 57 | 58 | # vcenter 59 | host = "vcenter.host" # vcenter 的地址 60 | user = "administrator@vsphere.local" # vcenter 的用户名 61 | pwd = "password" # vcenter 的密码 62 | port = 443 # vcenter 的端口 63 | 64 | # esxi 65 | esxi_names = [] # 需要采集的 esxi ,留空则全部采集 66 | 67 | # datastore 68 | datastore_names = [] # 需要采集的 datastore ,留空则全部采集 69 | 70 | # vm 71 | vm_enable = True # 是否要采集虚拟机信息 72 | vm_names = [ # 需要采集的虚拟机,留空则全部采集 73 | "vm1", 74 | "vm2", 75 | "vm3" 76 | ] 77 | ``` 78 | 79 | #### 运行 80 | 先尝试跑一下,假定 `vsphere-monitor` 放在 `/opt` 下 81 | ``` 82 | /opt/vsphere-monitor/env/bin/python /opt/vsphere-monitor/vsphere-monitor.py 83 | ``` 84 | 没有问题的话,将他放入定时任务 85 | ``` 86 | crontab -e 87 | 0-59/1 * * * * /opt/vsphere-monitor/env/bin/python /opt/vsphere-monitor/vsphere-monitor.py 88 | ``` 89 | 90 | #### 问题 91 | 部分 vm 可能会采集不到 `vm.net.if.in` 和 `vm.net.if.out` 指标,这是因为网络指标是通过 `vsphere` 的 `PerformanceManager` 采集的。可以在 `vcenter` 中查看虚拟机的 `性能` 图表时,也会发现显示错误 `未指定衡量指标` 或者 `No Metric Specified` 。这是 `vmware` 的 bug,在 `vSphere 6.0 Update 1` 以上版本被修复 92 | 93 | 详见官方 Knowledge —— [在 VMware vSphere Client 6.0 中查看虚拟机网络的实时性能图表时显示错误:未指定衡量指标 (2125021)](https://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=2125021) 94 | 95 | #### 截图 96 | esxi 97 | ![](https://github.com/freedomkk-qfeng/vsphere-monitor/blob/master/screenshots/esxi.png?raw=true) 98 | vm 99 | ![](https://github.com/freedomkk-qfeng/vsphere-monitor/blob/master/screenshots/vm.png?raw=true) 100 | -------------------------------------------------------------------------------- /config.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | # falcon 3 | endpoint = "vcenter" # 上报给 open-falcon 的 endpoint 4 | push_api = "http://127.0.0.1:6060/api/push" # 上报的 http api 接口 5 | interval = 60 # 上报的 step 间隔 6 | 7 | # vcenter 8 | host = "vcenter.host" # vcenter 的地址 9 | user = "administrator@vsphere.local" # vcenter 的用户名 10 | pwd = "password" # vcenter 的密码 11 | port = 443 # vcenter 的端口 12 | 13 | # esxi 14 | esxi_names = [] # 需要采集的 esxi ,留空则全部采集 15 | 16 | # datastore 17 | datastore_names = [] # 需要采集的 datastore ,留空则全部采集 18 | 19 | # vm 20 | vm_enable = True # 是否要采集虚拟机信息 21 | vm_names = [ # 需要采集的虚拟机,留空则全部采集 22 | "vm1", 23 | "vm2", 24 | "vm3" 25 | ] -------------------------------------------------------------------------------- /requirement.txt: -------------------------------------------------------------------------------- 1 | pyvmomi 2 | requests 3 | -------------------------------------------------------------------------------- /screenshots/esxi.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/freedomkk-qfeng/vsphere-monitor/a06c50f7d6b95b03d867346a5975e5158f77a982/screenshots/esxi.png -------------------------------------------------------------------------------- /screenshots/vm.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/freedomkk-qfeng/vsphere-monitor/a06c50f7d6b95b03d867346a5975e5158f77a982/screenshots/vm.png -------------------------------------------------------------------------------- /vsphere-monitor.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | #coding=utf-8 3 | 4 | """ 5 | Written by freedomkk-qfeng 6 | Github: https://github.com/freedomkk-qfeng 7 | Email: freedomkk_qfeng@qq.com 8 | Script to get vSphere metrics and push to Open-Falcon 9 | Version 0.2 10 | """ 11 | 12 | import atexit 13 | from pyVmomi import vim, vmodl 14 | from pyVim.connect import SmartConnectNoSSL, Disconnect 15 | import sys 16 | import copy 17 | import requests 18 | import time 19 | import json 20 | import config 21 | from datetime import timedelta 22 | 23 | def VmInfo(vm,content,vchtime,interval,perf_dict,tags): 24 | try: 25 | statInt = interval/20 26 | summary = vm.summary 27 | stats = summary.quickStats 28 | 29 | uptime = stats.uptimeSeconds 30 | add_data("vm.uptime",uptime,"GAUGE",tags) 31 | 32 | cpuUsage = 100 * float(stats.overallCpuUsage)/float(summary.runtime.maxCpuUsage) 33 | add_data("vm.cpu.usage",cpuUsage,"GAUGE",tags) 34 | 35 | memoryUsage = stats.guestMemoryUsage * 1024 * 1024 36 | add_data("vm.memory.usage",memoryUsage,"GAUGE",tags) 37 | 38 | memoryCapacity = summary.runtime.maxMemoryUsage * 1024 * 1024 39 | add_data("vm.memory.capacity",memoryCapacity,"GAUGE",tags) 40 | 41 | freeMemoryPercentage = 100 - ( 42 | (float(memoryUsage) / memoryCapacity) * 100 43 | ) 44 | add_data("vm.memory.freePercent",freeMemoryPercentage,"GAUGE",tags) 45 | 46 | statDatastoreRead = BuildQuery(content, vchtime, (perf_id(perf_dict, 'datastore.read.average')),"*", vm, interval) 47 | DatastoreRead = (float(sum(statDatastoreRead[0].value[0].value) * 1024) / statInt) 48 | add_data("vm.datastore.io.read_bytes",DatastoreRead,"GAUGE",tags) 49 | 50 | statDatastoreWrite = BuildQuery(content, vchtime, (perf_id(perf_dict, 'datastore.write.average')),"*", vm, interval) 51 | DatastoreWrite = (float(sum(statDatastoreWrite[0].value[0].value) * 1024) / statInt) 52 | add_data("vm.datastore.io.write_bytes",DatastoreWrite,"GAUGE",tags) 53 | 54 | statDatastoreIoRead = BuildQuery(content, vchtime, (perf_id(perf_dict, 'datastore.numberReadAveraged.average')),"*", vm, interval) 55 | DatastoreIoRead = (float(sum(statDatastoreIoRead[0].value[0].value)) / statInt) 56 | add_data("vm.datastore.io.read_numbers",DatastoreIoRead,"GAUGE",tags) 57 | 58 | statDatastoreIoWrite = BuildQuery(content, vchtime, (perf_id(perf_dict, 'datastore.numberWriteAveraged.average')),"*", vm, interval) 59 | DatastoreIoWrite = (float(sum(statDatastoreIoWrite[0].value[0].value)) / statInt) 60 | add_data("vm.datastore.io.write_numbers",DatastoreIoWrite,"GAUGE",tags) 61 | 62 | statDatastoreLatRead = BuildQuery(content, vchtime, (perf_id(perf_dict, 'datastore.totalReadLatency.average')), "*", vm, interval) 63 | DatastoreLatRead = (float(sum(statDatastoreLatRead[0].value[0].value)) / statInt) 64 | add_data("vm.datastore.io.read_latency",DatastoreLatRead,"GAUGE",tags) 65 | 66 | statDatastoreLatWrite = BuildQuery(content, vchtime, (perf_id(perf_dict, 'datastore.totalWriteLatency.average')), "*", vm, interval) 67 | DatastoreLatWrite = (float(sum(statDatastoreLatWrite[0].value[0].value)) / statInt) 68 | add_data("vm.datastore.io.write_latency",DatastoreLatWrite,"GAUGE",tags) 69 | 70 | statNetworkTx = BuildQuery(content, vchtime, (perf_id(perf_dict, 'net.transmitted.average')), "", vm, interval) 71 | if statNetworkTx != False: 72 | networkTx = (float(sum(statNetworkTx[0].value[0].value) * 8 * 1024) / statInt) 73 | add_data("vm.net.if.out",networkTx,"GAUGE",tags) 74 | statNetworkRx = BuildQuery(content, vchtime, (perf_id(perf_dict, 'net.received.average')), "", vm, interval) 75 | if statNetworkRx != False: 76 | networkRx = (float(sum(statNetworkRx[0].value[0].value) * 8 * 1024) / statInt) 77 | add_data("vm.net.if.in",networkRx,"GAUGE",tags) 78 | 79 | except Exception as error: 80 | print "Unable to access information for host: ", vm.name 81 | print error 82 | pass 83 | 84 | def HostInformation(host,datacenter_name,computeResource_name,content,perf_dict,vchtime,interval): 85 | try: 86 | statInt = interval/20 87 | summary = host.summary 88 | stats = summary.quickStats 89 | hardware = host.hardware 90 | 91 | tags = "datacenter=" + datacenter_name + ",cluster_name=" + computeResource_name + ",host=" + host.name 92 | 93 | uptime = stats.uptime 94 | add_data("esxi.uptime",uptime,"GAUGE",tags) 95 | 96 | cpuUsage = 100 * 1000 * 1000 * float(stats.overallCpuUsage) / float(hardware.cpuInfo.numCpuCores * hardware.cpuInfo.hz) 97 | add_data("esxi.cpu.usage",cpuUsage,"GAUGE",tags) 98 | 99 | memoryCapacity = hardware.memorySize 100 | add_data("esxi.memory.capacity",memoryCapacity,"GAUGE",tags) 101 | 102 | memoryUsage = stats.overallMemoryUsage * 1024 * 1024 103 | add_data("esxi.memory.usage",memoryUsage,"GAUGE",tags) 104 | 105 | freeMemoryPercentage = 100 - ( 106 | (float(memoryUsage) / memoryCapacity) * 100 107 | ) 108 | add_data("esxi.memory.freePercent",freeMemoryPercentage,"GAUGE",tags) 109 | 110 | statNetworkTx = BuildQuery(content, vchtime, (perf_id(perf_dict, 'net.transmitted.average')), "", host, interval) 111 | networkTx = (float(sum(statNetworkTx[0].value[0].value) * 8 * 1024) / statInt) 112 | add_data("esxi.net.if.out",networkTx,"GAUGE",tags) 113 | 114 | statNetworkRx = BuildQuery(content, vchtime, (perf_id(perf_dict, 'net.received.average')), "", host, interval) 115 | networkRx = (float(sum(statNetworkRx[0].value[0].value) * 8 * 1024) / statInt) 116 | add_data("esxi.net.if.in",networkRx,"GAUGE",tags) 117 | 118 | add_data("esxi.alive",1,"GAUGE",tags) 119 | 120 | except Exception as error: 121 | print "Unable to access information for host: ", host.name 122 | print error 123 | pass 124 | 125 | def perf_id(perf_dict, counter_name): 126 | counter_key = perf_dict[counter_name] 127 | return counter_key 128 | 129 | def ComputeResourceInformation(computeResource,datacenter_name,content,perf_dict,vchtime,interval): 130 | try: 131 | hostList = computeResource.host 132 | computeResource_name = computeResource.name 133 | for host in hostList: 134 | if (host.name in config.esxi_names) or (len(config.esxi_names) == 0): 135 | HostInformation(host,datacenter_name,computeResource_name,content,perf_dict,vchtime,interval) 136 | except Exception as error: 137 | print "Unable to access information for compute resource: ", 138 | computeResource.name 139 | print error 140 | pass 141 | 142 | def DatastoreInformation(datastore,datacenter_name): 143 | try: 144 | summary = datastore.summary 145 | name = summary.name 146 | TYPE = summary.type 147 | 148 | tags = "datacenter=" + datacenter_name + ",datastore=" + name + ",type=" + TYPE 149 | 150 | capacity = summary.capacity 151 | add_data("datastore.capacity",capacity,"GAUGE",tags) 152 | 153 | freeSpace = summary.freeSpace 154 | add_data("datastore.free",freeSpace,"GAUGE",tags) 155 | 156 | freeSpacePercentage = (float(freeSpace) / capacity) * 100 157 | add_data("datastore.freePercent",freeSpacePercentage,"GAUGE",tags) 158 | 159 | except Exception as error: 160 | print "Unable to access summary for datastore: ", datastore.name 161 | print error 162 | pass 163 | 164 | def add_data(metric,value,conterType,tags): 165 | data = {"endpoint":endpoint,"metric":metric,"timestamp":ts,"step":interval,"value":value,"counterType":conterType,"tags":tags} 166 | payload.append(copy.copy(data)) 167 | 168 | def run(host,user,pwd,port,interval): 169 | try: 170 | si = SmartConnectNoSSL(host=host, user=user, pwd=pwd, port=port) 171 | atexit.register(Disconnect, si) 172 | content = si.RetrieveContent() 173 | vchtime = si.CurrentTime() 174 | 175 | perf_dict = {} 176 | perfList = content.perfManager.perfCounter 177 | for counter in perfList: 178 | counter_full = "{}.{}.{}".format(counter.groupInfo.key, counter.nameInfo.key, counter.rollupType) 179 | perf_dict[counter_full] = counter.key 180 | 181 | for datacenter in content.rootFolder.childEntity: 182 | datacenter_name = datacenter.name.encode("utf8") 183 | datastores = datacenter.datastore 184 | for ds in datastores: 185 | if (ds.name in config.datastore_names) or (len(config.datastore_names) == 0): 186 | DatastoreInformation(ds,datacenter_name) 187 | 188 | if hasattr(datacenter.hostFolder, 'childEntity'): 189 | hostFolder = datacenter.hostFolder 190 | computeResourceList = [] 191 | computeResourceList = getComputeResource(hostFolder,computeResourceList) 192 | for computeResource in computeResourceList: 193 | ComputeResourceInformation(computeResource,datacenter_name,content,perf_dict,vchtime,interval) 194 | 195 | if config.vm_enable == True: 196 | obj = content.viewManager.CreateContainerView(content.rootFolder, [vim.VirtualMachine], True) 197 | for vm in obj.view: 198 | if (vm.name in config.vm_names) or (len(config.vm_names) == 0): 199 | tags = "vm=" + vm.name 200 | if vm.runtime.powerState == "poweredOn": 201 | VmInfo(vm, content, vchtime, interval, perf_dict, tags) 202 | add_data("vm.power",1,"GAUGE",tags) 203 | else: 204 | add_data("vm.power",0,"GAUGE",tags) 205 | 206 | except vmodl.MethodFault as error: 207 | print "Caught vmodl fault : " + error.msg 208 | return False, error.msg 209 | return True, "ok" 210 | 211 | def getComputeResource(Folder,computeResourceList): 212 | if hasattr(Folder, 'childEntity'): 213 | for computeResource in Folder.childEntity: 214 | getComputeResource(computeResource,computeResourceList) 215 | else: 216 | computeResourceList.append(Folder) 217 | return computeResourceList 218 | 219 | def hello_vcenter(vchost,username,password,port): 220 | try: 221 | si = SmartConnectNoSSL( 222 | host=vchost, 223 | user=username, 224 | pwd=password, 225 | port=port) 226 | 227 | atexit.register(Disconnect, si) 228 | return True, "ok" 229 | except vmodl.MethodFault as error: 230 | return False, error.msg 231 | except Exception as e: 232 | return False, str(e) 233 | 234 | 235 | def BuildQuery(content, vchtime, counterId, instance, entity, interval): 236 | perfManager = content.perfManager 237 | metricId = vim.PerformanceManager.MetricId(counterId=counterId, instance=instance) 238 | startTime = vchtime - timedelta(seconds=(interval + 60)) 239 | endTime = vchtime - timedelta(seconds=60) 240 | query = vim.PerformanceManager.QuerySpec(intervalId=20, entity=entity, metricId=[metricId], startTime=startTime, 241 | endTime=endTime) 242 | perfResults = perfManager.QueryPerf(querySpec=[query]) 243 | if perfResults: 244 | return perfResults 245 | else: 246 | return False 247 | 248 | if __name__ == "__main__": 249 | host = config.host 250 | user = config.user 251 | pwd = config.pwd 252 | port = config.port 253 | 254 | endpoint = config.endpoint 255 | push_api = config.push_api 256 | interval = config.interval 257 | 258 | ts = int(time.time()) 259 | payload = [] 260 | 261 | success, msg = hello_vcenter(host,user,pwd,port) 262 | if success == False: 263 | print msg 264 | add_data("vcenter.alive",0,"GAUGE","") 265 | #print json.dumps(payload,indent=4) 266 | r= requests.post(push_api, data=json.dumps(payload)) 267 | sys.exit(1) 268 | add_data("vcenter.alive",1,"GAUGE","") 269 | 270 | run(host,user,pwd,port,interval) 271 | #print json.dumps(payload,indent=4) 272 | r = requests.post(push_api, data=json.dumps(payload)) 273 | 274 | --------------------------------------------------------------------------------