├── .gitignore ├── LICENSE ├── README.md ├── USERS ├── doc ├── zas-agent-0.1.1.pdf └── zas_agent.py.1 ├── etc ├── network.scenario └── zas_scenario.cfg ├── install └── check_python_packages.py ├── setup.py └── src ├── test1.ingest ├── test2.ingest └── zas_agent.py /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | .idea/.name 3 | 4 | .idea/misc.xml 5 | 6 | .idea/modules.xml 7 | 8 | .idea/vcs.xml 9 | 10 | .idea/workspace.xml 11 | 12 | .idea/zas_agent.iml 13 | 14 | build/scripts-2.6/zas_agent.py 15 | 16 | UNKNOWN.egg-info/top_level.txt 17 | 18 | *.egg 19 | 20 | UNKNOWN.egg-info/dependency_links.txt 21 | 22 | UNKNOWN.egg-info/PKG-INFO 23 | 24 | UNKNOWN.egg-info/SOURCES.txt 25 | 26 | zas_agent.egg-info/dependency_links.txt 27 | 28 | zas_agent.egg-info/PKG-INFO 29 | 30 | zas_agent.egg-info/requires.txt 31 | 32 | zas_agent.egg-info/SOURCES.txt 33 | 34 | zas_agent.egg-info/top_level.txt 35 | 36 | .idea/inspectionProfiles/profiles_settings.xml 37 | 38 | .idea/inspectionProfiles/Project_Default.xml 39 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | 341 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # zas_agent 2 | Zabbix Agent Simulator 3 | 4 | Please look at the PDF documentation in the ./doc directory 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /USERS: -------------------------------------------------------------------------------- 1 | In this file, I will list the projects, which benefits from 2 | the use of the zas_agent. 3 | 4 | 1. Zabbix-Grafona integration 5 | 6 | URL: 7 | 8 | http://play.grafana-zabbix.org/ 9 | 10 | DEMO: 11 | 12 | http://play.grafana-zabbix.org/dashboard/db/template-linux-server -------------------------------------------------------------------------------- /doc/zas-agent-0.1.1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vulogov/zas_agent/b8f537a960f319e968b752899609101661fd77d4/doc/zas-agent-0.1.1.pdf -------------------------------------------------------------------------------- /doc/zas_agent.py.1: -------------------------------------------------------------------------------- 1 | .TH zas_agent.py 1 "Dec 2015" "Version 0.1.1" 2 | .SH NAME 3 | zas_agent.py - Zabbix Agent Simulator main program. 4 | .SH SYNOPSIS 5 | .B [ --listen --port --scenario 6 | .B --redis_host 7 | .B --redis_port 8 | .B --start 9 | .B --stop 10 | .B --ingest 11 | .B --rq_ingest 12 | .B --rq_cleanup 13 | .B --ingest_scenario 14 | .B --gen_ingest 15 | .B --ttl 16 | .B --rq_cleanup_full 17 | .B --log 18 | .B --daemonize 19 | .B --user 20 | .B --group 21 | .B ] 22 | 23 | .SH OPTIONS 24 | 25 | .IP --listen 26 | Listen IP 27 | .IP --port 28 | Listen port # 29 | .IP --scenario 30 | Path to the configuration file. 31 | .IP --redis_host 32 | Redis IP 33 | .IP --redis_port 34 | Redis port # 35 | .IP --start 36 | Start ZAS Agent 37 | .IP--stop 38 | Stop ZAS Agent 39 | .IP --ingest 40 | Send data to redis: metrics 41 | .IP --rq_ingest 42 | Send data to rqueue: queues 43 | .IP --rq_cleanup 44 | Cleanup rqueue: queues 45 | .IP --ingest_scenario 46 | Path to the file, containing scenario for the --ingest or --rq_ingest 47 | .IP --gen_ingest 48 | Ingest scenario into redis: metrics 49 | .IP --ttl 50 | "Time-to-live" for the values in redis: or rqueue: in seconds 51 | .IP --rq_cleanup_full 52 | If specified, zabbix_agent.py with --rq_cleanup will remove the last entry in the queue when the time comes 53 | .IP --log 54 | Path to the log file 55 | .IP --daemonize 56 | Daemonize application 57 | .IP --user 58 | Switch to the specific user 59 | .IP --group 60 | Switch to the specific group 61 | 62 | .SH EXAMPLES 63 | 64 | .PP 65 | .B Start ZAS agent daemon 66 | .PP 67 | zas_agent.py --start --daemonize 68 | .PP 69 | .B Stop ZAS agent daemon 70 | .PP 71 | zas_agent.py --stop 72 | .PP 73 | .B Ingest scenario and populate redis: values 74 | .PP 75 | zas_agent.py --ingest --ingest_scenario /etc/zas/network.scenario --ttl 10 76 | .PP 77 | .B Populate rqueue: queues as background service 78 | .PP 79 | zas_agent.py --rq_ingest --ingest_scenario /etc/zas/network.scenario --ttl 10 --daemonize --pid /tmp/network.scenario.pid 80 | .PP 81 | 82 | 83 | -------------------------------------------------------------------------------- /etc/network.scenario: -------------------------------------------------------------------------------- 1 | # Comment 2 | net.if.in[eth0]:{"min":0,"max":100000,"type":"int","variation_rnd":1,"spike_barrier":3,"spike_width":6} 3 | net.if.in[eth1]:{"min":0,"max":100000,"type":"int","variation_min":10,"variation_max":25} 4 | net.if.out[eth1]:{"min":0,"max":100000,"type":"int","variation_min":5,"variation_max":5} 5 | net.if.out[eth0]:{"min":0,"max":100000,"type":"int","variation_min":5,"variation_max":5,"spike_barrier":10,"spike_width":6} 6 | system.cpu.util[,,avg1]:{"min":0,"max":20,"type":"float","variation_min":10,"variation_max":10} 7 | -------------------------------------------------------------------------------- /etc/zas_scenario.cfg: -------------------------------------------------------------------------------- 1 | ## 2 | ## This target will match all vfs.fs.size[*,pfree] requests 3 | ## and generate uniform random numbers in range 1 to 100 4 | ## 5 | [filesystems.size pfree] 6 | match=vfs.fs.size\[(.?),pfree\] 7 | value=uniform:1,100 8 | [application.connections] 9 | value=uniform_int:1,100 10 | 11 | ## 12 | ## This target will match all vfs.fs.size[*,free] requests 13 | ## and request data from REDIS 14 | ## 15 | [filesystem.size free] 16 | match=vfs.fs.size\[(.?),free\] 17 | value=redis: 18 | [all net.if.in] 19 | match=net.if.in* 20 | value=redis: 21 | [all net.if.out] 22 | match=net.if.out* 23 | value=redis: 24 | ## 25 | ## Scenario calculations 26 | ## 27 | [all system.cpu.util] 28 | match=system.cpu.util* 29 | value=scenario: 30 | scenario={"min":0,"max":20,"type":"float","variation_min":10,"variation_max":10} 31 | 32 | ## 33 | ## This target will match all vfs.fs.size[*,used] requests 34 | ## and request data from REDIS lists 35 | ## 36 | [filesystem.size used] 37 | match=vfs.fs.size\[(.?),used\] 38 | value=rqueue: 39 | 40 | ## 41 | ## This target will match agent.ping requests 42 | ## and return static value 1 43 | [agent.ping] 44 | value=static:1 45 | -------------------------------------------------------------------------------- /install/check_python_packages.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | PKGS=['os','sys','ConfigParser','argparse','struct','multiprocessing','socket','time','logging','redis','numpy','fnmatch','re','signal','daemonize','simplejson'] 4 | 5 | for p in PKGS: 6 | import imp 7 | m_repr = "'%s'"%p 8 | m_repr = m_repr.ljust(20,".") 9 | print "Module %s"%m_repr, 10 | try: 11 | fp, pathname, description = imp.find_module(p) 12 | imp.load_module(p, fp, pathname, description) 13 | except: 14 | print "FAIL" 15 | continue 16 | finally: 17 | print "OK" 18 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | ## 2 | ## Installtion of the ZAS Agent 3 | ## 4 | 5 | from setuptools import setup 6 | 7 | setup( 8 | name="zas_agent", 9 | author="Vladimir Ulogov", 10 | author_email="vladimir.ulogov@zabbix.com", 11 | license="GNU GPLv3", 12 | description="zas_agent", 13 | long_description="Zabbix Agent Simulator", 14 | version="0.1.2", 15 | scripts=['src/zas_agent.py',], 16 | data_files=[ 17 | ("/etc/zas", ['etc/network.scenario'],), 18 | ("/etc", ["etc/zas_scenario.cfg"]), 19 | ("/usr/share/zas_agent", ["doc/zas-agent-0.1.1.pdf",]), 20 | ("/usr/share/man/man1", ["doc/zas_agent.py.1",]) 21 | ], 22 | install_requires=[ 23 | "daemonize == 2.4.2", 24 | "numpy == 1.22.0", 25 | "redis >= 2.0.0", 26 | "simplejson >= 2.0.9" 27 | ] 28 | ) 29 | -------------------------------------------------------------------------------- /src/test1.ingest: -------------------------------------------------------------------------------- 1 | system.cpu.util[,,argv1]:0.2 2 | -------------------------------------------------------------------------------- /src/test2.ingest: -------------------------------------------------------------------------------- 1 | vfs.fs.size[/,used]:2000 2 | vfs.fs.size[/,used]:1900 3 | vfs.fs.size[/,used]:2100 4 | 5 | -------------------------------------------------------------------------------- /src/zas_agent.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | ## 3 | ## 4 | ## Zabbix Passive Agent Simulator: version 0.1 5 | ## 6 | ## 7 | 8 | import os 9 | import sys 10 | import ConfigParser 11 | import argparse 12 | import struct 13 | import multiprocessing 14 | import socket 15 | import time 16 | import logging 17 | import subprocess 18 | 19 | ARGS=None 20 | SCENARIO=None 21 | 22 | 23 | ## 24 | ## Let's ingest single scenario to REDIS 25 | ## 26 | def ingest_scenario(r, key, scn): 27 | import numpy as np 28 | 29 | def push_spike_to_redis(r, key, array): 30 | k = "%s.spike"%key 31 | for v in array: 32 | r.rpush(k,v) 33 | def return_res(scn, val): 34 | if scn["type"] == "int": 35 | return int(val) 36 | return val 37 | 38 | s_min = float(scn["min"]) 39 | s_max = float(scn["max"]) 40 | if r.llen("%s.spike"%key) > 0: 41 | s_val = float(r.lpop("%s.spike"%key)) 42 | r.set(key,s_val) 43 | return return_res(scn,s_val) 44 | if scn.has_key("key"): 45 | req_key = scn["key"] 46 | else: 47 | req_key = key 48 | prev_val = r.get(req_key) 49 | if prev_val == None: 50 | prev_val = np.random.uniform(s_min,s_max) 51 | else: 52 | prev_val = float(prev_val) 53 | ## 54 | ## Throw the dice if there is a time for a spike 55 | ## 56 | if scn.has_key("spike_barrier") and scn.has_key("spike_width") and r.llen("%s.spike"%key) == 0: 57 | s_barrier = float(scn["spike_barrier"]) 58 | dice = np.random.uniform(0,100) 59 | if s_barrier > dice: 60 | ## Spike ! 61 | spike_max = np.random.uniform(prev_val,s_max) 62 | spike_min = np.random.uniform(spike_max, s_min) 63 | h_width = int(scn["spike_width"])/2 64 | h_plateu = int(np.random.uniform(1,h_width)) 65 | up = np.linspace(prev_val, spike_max, h_width) 66 | plateu = np.random.gamma(spike_max, 0.95,h_plateu) 67 | down = np.linspace(spike_max, spike_min, h_width) 68 | push_spike_to_redis(r,key,up) 69 | push_spike_to_redis(r,key,plateu) 70 | push_spike_to_redis(r,key,down) 71 | print "Spike!",dice,s_barrier,up,plateu,down 72 | 73 | 74 | if scn.has_key("variation_min") and scn.has_key("variation_max"): 75 | min_val = prev_val-(prev_val*0.01)*float(scn["variation_min"]) 76 | if min_val < s_min: 77 | min_val = s_min 78 | max_val = prev_val+(prev_val*0.01)*float(scn["variation_max"]) 79 | if max_val > s_max: 80 | max_val = s_max 81 | cur_val = np.random.uniform(min_val, max_val) 82 | elif scn.has_key("variation_rnd") and scn["variation_rnd"] == 1: 83 | min_val = np.random.uniform(float(scn["min"]),float(prev_val)) 84 | max_val = np.random.uniform(float(prev_val),float(scn["max"])) 85 | cur_val = np.random.uniform(min_val, max_val) 86 | else: 87 | cur_val = np.random.uniform(float(scn["min"]),float(scn["max"])) 88 | cur_val = return_res(scn,cur_val) 89 | r.set(key,cur_val) 90 | return cur_val 91 | 92 | ## 93 | ## def handle(connection, address, scenario, args) 94 | ## agent request handler 95 | ## - connection: Incoming connection handler 96 | ## - address: Incoming address 97 | ## - scenario: Initial simulation scenario 98 | ## - args: Passed parameters which were passed to the main program 99 | ## 100 | 101 | 102 | def handle(connection, address, scenario, args): 103 | import logging 104 | 105 | ## 106 | ## Working with keys: 107 | ## locate_key(scenario, data) 108 | ## locate key requested by zabbix_get in the scenario 109 | ## - scenario: current scenario 110 | ## - data: data passed from zabbix_get 111 | ## 112 | def locate_key(scenario, data): 113 | import fnmatch,re 114 | 115 | key = data.strip() 116 | if key in scenario.sections(): 117 | return (scenario.get(key, "value"),key) 118 | else: 119 | for s in scenario.sections(): 120 | try: 121 | patt = scenario.get(s, "match") 122 | except: 123 | continue 124 | if patt == key or fnmatch.fnmatch(key, patt) or re.match(patt, key) != None: 125 | return (scenario.get(s, "value"),s) 126 | return (None,None) 127 | 128 | ## 129 | ## Generate data 130 | ## 131 | 132 | ## 133 | ## Generating random data within the range val=low,high 134 | ## 135 | def generate_random_uniform(val): 136 | import numpy as np 137 | try: 138 | low,high = val.split(",") 139 | return np.random.uniform(float(low),float(high)) 140 | except: 141 | return None 142 | ## 143 | ## Request data from REDIS store 144 | ## - host: Redis IP 145 | ## - port: Redis port 146 | ## - val: data passed from zabbix_agent 147 | ## 148 | def get_data_from_redis(host, port, val): 149 | import redis 150 | try: 151 | r = redis.Redis(host=host, port=port, db=0) 152 | res = r.get(val) 153 | del r 154 | return res 155 | except: 156 | return None 157 | ## 158 | ## Request data from REDIS store which were stored in the list 159 | ## This function requests the last data in the list 160 | ## You must apped data to the list with LPUSH 161 | ## - host: Redis IP 162 | ## - port: Redis port 163 | ## - val: data passed from zabbix_agent 164 | ## 165 | def get_data_from_redis_queue(host, port, val): 166 | import redis 167 | try: 168 | r = redis.Redis(host=host, port=port, db=1) 169 | res = r.lindex(val, r.llen(val)-1) 170 | del r 171 | return res 172 | except: 173 | return None 174 | 175 | def get_data_from_scenario_execution(host, port, r_key, scn): 176 | import redis 177 | import simplejson 178 | 179 | try: 180 | p_scn = simplejson.loads(scn) 181 | r = redis.Redis(host=host, port=port, db=2) 182 | res = ingest_scenario(r,r_key,p_scn) 183 | return res 184 | except: 185 | return None 186 | 187 | ## 188 | ## Handler for the Zabbix protocol V 1 189 | ## 190 | def protocol_v1(scenario, args, data): 191 | value, scn_key = locate_key(scenario, data) 192 | if not value or not scn_key: 193 | return None 194 | ix = value.index(":") 195 | v_type, val = value[:ix],value[ix+1:].strip() 196 | v_type = v_type.lower() 197 | if v_type == "static": 198 | return str(val) 199 | elif v_type == "cmd": 200 | call_args = val.split(',') 201 | res = subprocess.Popen(call_args, stdout=subprocess.PIPE).stdout.read() 202 | return res.strip() 203 | elif v_type == "uniform_int": 204 | res = generate_random_uniform(val) 205 | if not res: 206 | return res 207 | else: 208 | return str(int(res)) 209 | elif v_type == "uniform": 210 | try: 211 | return str(generate_random_uniform(val)) 212 | except: 213 | return None 214 | elif v_type == "redis": 215 | if len(val) == 0: 216 | r_key = data 217 | else: 218 | r_key = val 219 | res =get_data_from_redis(args.redis_host, args.redis_port, r_key) 220 | if not res: 221 | return None 222 | return str(res) 223 | elif v_type == "rqueue": 224 | if len(val) == 0: 225 | r_key = data 226 | else: 227 | r_key = val 228 | res =get_data_from_redis_queue(args.redis_host, args.redis_port, r_key) 229 | if not res: 230 | return None 231 | return str(res) 232 | elif v_type == "scenario": 233 | if len(val) == 0: 234 | r_key = data 235 | else: 236 | r_key = val 237 | try: 238 | scn = scenario.get(scn_key, "scenario") 239 | except: 240 | return None 241 | return str(get_data_from_scenario_execution(args.redis_host, args.redis_port, r_key, scn)) 242 | else: 243 | return None 244 | 245 | logging.basicConfig(level=logging.DEBUG) 246 | logger = logging.getLogger("process-%r" % (address,)) 247 | try: 248 | logger.debug("Connected %r at %r", connection, address) 249 | while True: 250 | try: 251 | data = connection.recv(1024) 252 | except: 253 | break 254 | try: 255 | hdr = struct.unpack("ssssB", data[:5]) 256 | except: 257 | break 258 | sig = "".join(list(hdr[:4])) 259 | ver = list(hdr)[-1] 260 | if sig != "ZBXD": 261 | ver=10 262 | else: 263 | p_len = struct.unpack("L", data[5:13])[0] 264 | if p_len < 0 and p_len > 1024: 265 | logger.debug("Request is too small or too large") 266 | break 267 | data = data[13:] 268 | if data == "": 269 | logger.debug("Socket closed remotely") 270 | break 271 | if ver == 1: 272 | data = data.strip() 273 | r_data = protocol_v1(scenario, args, data) 274 | else: 275 | data = data.strip() 276 | r_data = protocol_v1(scenario, args, data) 277 | if not r_data: 278 | logger.debug("Can not locate value for the key %s in scenario"%data) 279 | break 280 | if ver in [1,10]: 281 | hdr="ZBXD"+struct.pack("B",1)+struct.pack("L",len(r_data)+1) 282 | connection.sendall(hdr+r_data+"\n") 283 | logger.debug("Sent data: %s=%s"%(repr(data),r_data)) 284 | break 285 | except: 286 | logger.exception("Problem handling request") 287 | finally: 288 | logger.debug("Closing socket") 289 | try: 290 | connection.close() 291 | except: 292 | pass 293 | sys.exit(0) 294 | 295 | ## 296 | ## Implementation of the TCP multiprocessing Server 297 | ## 298 | class Server(object): 299 | def __init__(self, hostname, port, scenario, _args): 300 | import logging 301 | self.logger = logging.getLogger("zas_server") 302 | self.hostname = hostname 303 | self.port = port 304 | self.scenario = scenario 305 | self.args = _args 306 | 307 | def start(self): 308 | global SCENARIO 309 | self.logger.debug("listening") 310 | try: 311 | self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 312 | self.socket.bind((self.hostname, self.port)) 313 | self.socket.listen(socket.SOMAXCONN) 314 | except: 315 | self.logger.debug("Can not bind to %s:%d"%(self.hostname, self.port)) 316 | sys.exit(0) 317 | while True: 318 | conn, address = self.socket.accept() 319 | self.logger.debug("Got connection") 320 | process = multiprocessing.Process(target=handle, args=(conn, address, self.scenario, self.args)) 321 | process.daemon = True 322 | process.start() 323 | self.logger.debug("Started process %r", process) 324 | 325 | 326 | ## 327 | ## Feed the REDIS with pseudo-random stuff 328 | ## 329 | def gen_ingest(): 330 | global ARGS 331 | args = ARGS 332 | 333 | import redis 334 | 335 | ## 336 | ## Calculate percentage 337 | ## 338 | def percentage(part, whole): 339 | return 100 * float(part)/float(whole) 340 | ## 341 | ## Let's read ingestion scenario 342 | ## 343 | def parse_ingestion_scenario(fname): 344 | import simplejson 345 | 346 | logger = logging.getLogger("zas_ingestor") 347 | if not os.path.exists(fname): 348 | logger.error("Ingestion scenario file %s not exists"%fname) 349 | return {} 350 | f = open(fname) 351 | scn = {} 352 | lines = f.readlines() 353 | for l in lines: 354 | if l[0] in ["#", ";"]: 355 | ## This is comment 356 | continue 357 | ix = l.index(":") 358 | s_key,s_scn = l[:ix],l[ix+1:].strip() 359 | try: 360 | scn[s_key] = simplejson.loads(s_scn) 361 | except: 362 | continue 363 | return scn 364 | 365 | logger = logging.getLogger("zas_ingestor") 366 | while True: 367 | r = redis.Redis(host=ARGS.redis_host, port=ARGS.redis_port, db=0) 368 | scn = parse_ingestion_scenario(ARGS.ingest_scenario) 369 | logger.debug("%d keys are found in ingestion scenario"%len(scn.keys())) 370 | for k in scn.keys(): 371 | ingest_scenario(r,k,scn[k]) 372 | del r 373 | time.sleep(ARGS.ttl) 374 | 375 | ## 376 | ## Fill the REDIS with stuff from files 377 | ## 378 | def _ingest(ARGS, fun, use_ttl=False): 379 | if ARGS.ingest_file != "-" and os.path.exists(ARGS.ingest_file): 380 | f = open(ARGS.ingest_file) 381 | elif ARGS.ingest_file == "-": 382 | f = sys.stdin 383 | else: 384 | print "Ingest data file %s not found"%ARGS.ingest_file 385 | sys.exit() 386 | while True: 387 | line = f.readline().strip() 388 | if len(line) == 0: 389 | f.close() 390 | break 391 | if line[0] in ["#",";"]: 392 | continue 393 | ix = line.index(":") 394 | ig_key,ig_val = line[:ix],line[ix+1:] 395 | fun(ig_key, ig_val) 396 | if use_ttl: 397 | time.sleep(int(ARGS.ttl)) 398 | ## 399 | ## Ingest to redis: 400 | ## 401 | def ingest(ARGS): 402 | import redis 403 | 404 | r = redis.Redis(host=ARGS.redis_host, port=ARGS.redis_port, db=0) 405 | _ingest(ARGS, r.set) 406 | del r 407 | sys.exit(0) 408 | ## 409 | ## Ingest to rqueue: 410 | ## 411 | def rq_ingest(ARGS): 412 | import redis 413 | 414 | r = redis.Redis(host=ARGS.redis_host, port=ARGS.redis_port, db=1) 415 | _ingest(ARGS, r.lpush, True) 416 | del r 417 | sys.exit(0) 418 | 419 | ## 420 | ## Clean-up rqueue: 421 | ## 422 | def rq_cleanup(ARGS): 423 | import redis 424 | 425 | while True: 426 | time.sleep(int(ARGS.ttl)) 427 | r = redis.Redis(host=ARGS.redis_host, port=ARGS.redis_port, db=1) 428 | for key in r.keys(): 429 | if (r.llen(key) == 1 and ARGS.rq_cleanup_full) or r.llen(key) > 1: 430 | r.rpop(key) 431 | time.sleep(int(ARGS.ttl)) 432 | del r 433 | 434 | def trace(msg=None): 435 | import traceback 436 | f=open("/tmp/zas_trace.txt","a") 437 | if msg: 438 | f.write(msg+"\n") 439 | else: 440 | traceback.print_exc(file=f) 441 | f.close() 442 | ## 443 | ## Function MAIN() 444 | ## 445 | def main(): 446 | global ARGS 447 | args = ARGS 448 | 449 | if args.daemonize: 450 | logging.basicConfig(filename=args.log,level=logging.DEBUG) 451 | else: 452 | logging.basicConfig(level=logging.DEBUG) 453 | if not os.access(args.scenario, os.R_OK): 454 | logging.info("Configuration file %s not readable"%args.scenario) 455 | sys.exit(0) 456 | logging.info("Reading configuration file %s"%args.scenario) 457 | try: 458 | SCENARIO = ConfigParser.SafeConfigParser() 459 | SCENARIO.readfp(open(args.scenario)) 460 | except: 461 | print "Can not parse scenario file" 462 | sys.exit(0) 463 | server = Server(args.listen, args.port, SCENARIO, args) 464 | try: 465 | logging.info("Listening %s:%d"%(args.listen, args.port)) 466 | server.start() 467 | except: 468 | logging.exception("Unexpected exception") 469 | finally: 470 | logging.info("Shutting down") 471 | for process in multiprocessing.active_children(): 472 | logging.info("Shutting down process %r", process) 473 | process.terminate() 474 | process.join() 475 | logging.info("All done") 476 | ## 477 | ## Stop the daemon 478 | ## 479 | def stop(): 480 | global ARGS 481 | args = ARGS 482 | 483 | import time 484 | import signal 485 | 486 | if os.path.exists(args.pid): 487 | try: 488 | pid = int(open(args.pid).read()) 489 | except: 490 | print "Can not read PID of the ZAS" 491 | sys.exit(0) 492 | try: 493 | print "Terminating ZAS:", 494 | except: 495 | print "can't" 496 | finally: 497 | print "ok" 498 | os.kill(pid, signal.SIGTERM) 499 | time.sleep(5) 500 | print "Killing ZAS:", 501 | try: 502 | os.kill(pid, signal.SIGKILL) 503 | except: 504 | print "dead already" 505 | else: 506 | print "ZAS isn't running..." 507 | 508 | if __name__ == "__main__": 509 | from daemonize import Daemonize 510 | 511 | parser = argparse.ArgumentParser(description='Zabbix Agent Simulator') 512 | HOST, PORT = "0.0.0.0", 10050 513 | parser.add_argument('--listen', type=str, default=HOST, help='Listen IP') 514 | parser.add_argument('--port', type=int, default=PORT, help='Listen Port') 515 | parser.add_argument('--scenario', type=str, default="/etc/zas_scenario.cfg", help="Path to scenario configuration file") 516 | parser.add_argument('--redis_host', type=str, default="localhost", help='REDIS IP') 517 | parser.add_argument('--redis_port', type=int, default=6379, help='REDIS Port') 518 | parser.add_argument('--start', action='store_true', help="Start simulator") 519 | parser.add_argument('--stop', action='store_true', help="Stop simulator") 520 | parser.add_argument('--ingest', action='store_true', help="Ingest data into REDIS for redis: metrics") 521 | parser.add_argument('--rq_ingest', action='store_true', help='Ingest data into REDIS for rqueue: metrics') 522 | parser.add_argument('--ingest_file', type=str, default="-", help='Path to the data file') 523 | parser.add_argument('--rq_cleanup', action='store_true', help='Cleanup data from the rqueue: metrics') 524 | parser.add_argument('--gen_ingest', action='store_true', help='Read \"ingest scenario\" and feed redis: metrics') 525 | parser.add_argument('--ingest_scenario', type=str, default="-", help='Path to ingest scenario configuration file') 526 | parser.add_argument('--ttl', type=int, default=15, help='TTL (Time To Live) for the metrics (in seconds)') 527 | parser.add_argument('--rq_cleanup_full', action='store_true', help="Clean up queues to empty state") 528 | parser.add_argument("--log", type=str, default="/tmp/zas_agent.log", help="Name of the log file if agent is daemonized") 529 | parser.add_argument('--daemonize', action='store_true', help="Daemonize simulator") 530 | parser.add_argument('--pid', type=str, default="/tmp/zas_agent.pid", help="PID file for simulator process") 531 | parser.add_argument('--user', type=str, default="zabbix", help='Run simulator as this user') 532 | parser.add_argument('--group', type=str, default="zabbix", help='Run simulator with this GUID') 533 | 534 | 535 | try: 536 | ARGS = parser.parse_args() 537 | except Exception, msg: 538 | #traceback.print_exception() 539 | print "Error occurs:", msg 540 | parser.print_help() 541 | sys.exit(0) 542 | if not ARGS.stop and ARGS.start and not ARGS.gen_ingest: 543 | if not os.path.exists(ARGS.scenario) or not os.path.isfile(ARGS.scenario): 544 | print "Configuration file %s not exists or it is not a file"%ARGS.scenario 545 | sys.exit(0) 546 | if os.path.exists(ARGS.pid): 547 | print "ZAS Agent is already running ..." 548 | sys.exit(0) 549 | if ARGS.daemonize: 550 | print "Daemonizing ZAS:", 551 | try: 552 | daemon = Daemonize(app="zas_agent", pid=ARGS.pid, action=main, foreground=not ARGS.daemonize, user=ARGS.user, group=ARGS.group) 553 | daemon.start() 554 | except SystemExit: 555 | pass 556 | except: 557 | if ARGS.daemonize: 558 | print "fail" 559 | import traceback 560 | print '-'*60 561 | traceback.print_exc(file=sys.stdout) 562 | print '-'*60 563 | sys.stdout.flush() 564 | sys.exit(0) 565 | finally: 566 | if ARGS.daemonize: 567 | print "ok" 568 | elif ARGS.stop and not ARGS.start: 569 | stop() 570 | elif ARGS.ingest: 571 | ingest(ARGS) 572 | elif ARGS.rq_ingest: 573 | rq_ingest(ARGS) 574 | elif ARGS.rq_cleanup: 575 | rq_cleanup(ARGS) 576 | elif ARGS.gen_ingest and ARGS.start: 577 | if os.path.exists(ARGS.pid): 578 | print "ZAS Ingestor is already running ..." 579 | sys.exit(0) 580 | if ARGS.ingest_scenario == "-": 581 | print "ZAS Ingestor can not use STDIN for scenario file" 582 | sys.exit(0) 583 | daemon = Daemonize(app="zas_ingestor", pid=ARGS.pid, action=gen_ingest, foreground=not ARGS.daemonize, user=ARGS.user, group=ARGS.group) 584 | daemon.start() 585 | else: 586 | print "You have to specify --start or --stop" 587 | parser.print_help() 588 | 589 | --------------------------------------------------------------------------------