1
0
mirror of https://github.com/limosek/zaf.git synced 2025-10-31 17:47:37 +01:00

55 Commits
1.2 ... master

Author SHA1 Message Date
Lukas Macura
6913033874 Added tgz package support 2017-03-19 19:56:58 +01:00
Lukas Macura
8b81fea72c Repaired send operation 2017-02-15 15:35:16 +01:00
Lukas Macura
eaf83df311 Repaired zaf send 2017-02-14 17:05:16 +01:00
Lukas Macura
52386a624f Added docs 2017-01-30 14:23:41 +01:00
Lukas Macura
4489b9cafe One more typo repair 2017-01-30 11:14:33 +01:00
Lukas Macura
80ee4b6903 Repaired link 2017-01-30 11:03:49 +01:00
Lukas Macura
8ad7841525 Added link to my site 2017-01-30 10:59:09 +01:00
Lukas Macura
c4abfe9ea6 Updated docs 2017-01-30 10:47:59 +01:00
Lukas Macura
2977958dd5 Support for plugin subcommands 2017-01-30 10:32:29 +01:00
Lukas Macura
211d2fca39 Removed automatic installation of agent on debian 2017-01-05 15:52:59 +01:00
Lukas Macura
6174a043bc Repaired installation doc when non-ssl 2016-12-23 14:55:40 +01:00
Lukas Macura
56763de3fc Repaired warning durilg reinstall 2016-12-12 11:18:29 +01:00
Lukas Macura
c1f5eddb5d Repaired plugin reinstall 2016-12-12 11:07:11 +01:00
Lukas Macura
e826283c85 On package reinstall, all options are saved 2016-12-12 09:56:12 +01:00
Lukas Macura
e8be02436c Repaired preload 2016-12-11 21:05:18 +01:00
Lukas Macura
7f774f409d Added and documented itemsh command 2016-12-11 16:20:06 +01:00
Lukas Macura
6204eacd6a Repaired dependency checking on older debian systems 2016-12-11 14:58:05 +01:00
Lukas Macura
2b41fc57a5 Added documentation of plugin parameters 2016-12-11 13:10:35 +01:00
Lukas Macura
a9a0ff9528 Support for global plugin parameters 2016-12-11 13:06:05 +01:00
Lukas Macura
63b00e70aa Added return parameters checking 2016-12-09 12:40:25 +01:00
Lukas Macura
2ffc186d68 Make scripts nicer by unexpand 2016-12-07 14:25:34 +01:00
Lukas Macura
cfa056065b Added instructions of trunk 2016-12-07 13:19:21 +01:00
Lukas Macura
38927897dc Updated trunk versions 2016-12-07 13:17:16 +01:00
Lukas Macura
2e8a27e6ac Plugins can be entered divided by comas 2016-12-07 12:51:15 +01:00
Lukas Macura
25d47e6ba8 Updated doc for wget 2016-12-05 12:17:34 +01:00
Lukas Macura
71a79ed57f Added possibility to use wget 2016-12-05 12:03:13 +01:00
Lukas Macura
9ac7bd34d4 Repaired plugin (re)installation 2016-12-05 11:30:10 +01:00
Lukas Macura
0ef05853a4 Plugin installation is possible offline
Plugin postconfiguration will be called on zaf agent-config
2016-12-02 13:12:13 +01:00
Lukas Macura
3e2f1502d1 Simplified caching 2016-12-02 09:44:48 +01:00
Lukas Macura
407fb2f77f Repaired and reworked caching 2016-12-01 16:57:26 +01:00
Lukas Macura
bc1cbaf144 If OS_PKG unset, ignore dependencies 2016-12-01 11:16:11 +01:00
Lukas Macura
4842cdaee1 Cache locking support 2016-12-01 10:28:14 +01:00
Lukas Macura
336d120bb5 Added better documentation of install options 2016-11-30 16:57:18 +01:00
Lukas Macura
b535eb58e2 Added proxy setting support 2016-11-30 16:40:26 +01:00
Lukas Macura
6697df6519 More environment checking before autodetection for offline install 2016-11-28 15:54:08 +01:00
Lukas Macura
92b3b626aa Env variable has precedence over autodetection 2016-11-28 15:28:14 +01:00
Lukas Macura
79c1992f56 Error checking moved to common functions 2016-11-28 15:17:24 +01:00
Lukas Macura
0d6fd293a3 README.md is not installed by default 2016-11-28 14:08:42 +01:00
Lukas Macura
1c876c756c Better error checking on install 2016-11-28 13:53:51 +01:00
Lukas Macura
8e8e1b9dfc Repaired git detection 2016-11-28 13:28:25 +01:00
Lukas Macura
375f805b6a Repaired setting option 2016-11-26 17:52:00 +01:00
Lukas Macura
ce843ddd55 Quiet error when zabbix user is not found 2016-11-22 15:19:28 +01:00
Lukas Macura
5838292856 Added postconf hook for openwrt systems 2016-11-22 14:27:44 +01:00
Lukas Macura
cc244ef791 When cache is in tmp, automaticaly create it 2016-11-22 14:03:27 +01:00
Lukas Macura
006a9fc99b which => zaf_which 2016-11-21 18:20:03 +01:00
Lukas Macura
72ef383146 Internal which now search in more dirs 2016-11-21 17:11:30 +01:00
Lukas Macura
b80fd5ce7f Missed zaf_which 2016-11-21 17:05:13 +01:00
Lukas Macura
f72488708b Repaired 'which' detection and user environment checking 2016-11-21 16:59:59 +01:00
Lukas Macura
f110e9aec7 Repaired version numbers 2016-06-17 14:06:27 +02:00
Lukas Macura
b9551fb2f2 Repaired merge of trunk
External items are working now
2016-06-17 13:16:07 +02:00
Lukas Macura
8e9d950411 Merge branch '1.2' 2016-06-17 12:07:14 +02:00
Lukas Macura
93b482dc69 New package management
Repaired install
Added external item support
2016-06-17 11:58:43 +02:00
Lukas Macura
3ad71262e2 Merge pull request #1 from kovetskiy/master
package for archlinux
2016-06-16 14:22:16 +02:00
Egor Kovetskiy
c2316d2341 package for archlinux 2016-06-16 12:07:08 +06:00
Lukas Macura
f9584ff673 Updated version in master 2016-04-18 10:38:43 +02:00
28 changed files with 1872 additions and 884 deletions

View File

@@ -1,12 +1,22 @@
# Zabbix agent framework makefile # Zabbix agent framework makefile
all: help
help:
@echo make '{deb|arch|ipk|rpm}' '[PLUGINS="/dir/plg1 [/dir2]...] [IPLUGINS="plg1 [plg2]..."] [ZAF_OPTIONS="ZAF_cfg=val ..."] [AGENT_OPTIONS="Z_Server=host ..."]'
@echo PLUGINS are embedded into package. Has to be local directories accessible during build.
@echo IPLUGINS will be downloaded and installed after package is installed. Can be name or url accessible after package installation.
@echo
include deb.mk
include arch.mk
include ipk.mk
include rpm.mk
include tgz.mk
CONTROLFILES=$(foreach p,$(PLUGINS),$(p)/control.zaf) CONTROLFILES=$(foreach p,$(PLUGINS),$(p)/control.zaf)
ZAF_EXPORT_OPTS=$(foreach o,$(ZAF_OPTIONS),$(shell echo $(o)|cut -d '=' -f 1)) ZAF_EXPORT_OPTS=$(foreach o,$(ZAF_OPTIONS),$(shell echo $(o)|cut -d '=' -f 1))
DEBIAN_DIR=tmp/deb
DEBIAN_CTRL=$(DEBIAN_DIR)/DEBIAN
ifeq ($(DEBIAN_PKG),)
DEBIAN_PKG=$(shell . lib/zaf.lib.sh; echo out/zaf-$$ZAF_VERSION.deb)
endif
ifeq ($(ZAF_DEBUG),) ifeq ($(ZAF_DEBUG),)
ZAF_DEBUG=0 ZAF_DEBUG=0
endif endif
@@ -18,79 +28,18 @@ ifeq ($(IPLUGINS),)
IPLUGINS = zaf IPLUGINS = zaf
endif endif
all: help
help:
@echo make '{deb|ipk|rpm}' '[PLUGINS="/dir/plg1 [/dir2]...] [IPLUGINS="plg1 [plg2]..."] [ZAF_OPTIONS="ZAF_cfg=val ..."] [AGENT_OPTIONS="Z_Server=host ..."]'
@echo PLUGINS are embedded into package. Has to be local directories accessible during build.
@echo IPLUGINS will be downloaded and installed after package is installed. Can be name or url accessible after package installation.
@echo
deb: $(DEBIAN_PKG) deb: $(DEBIAN_PKG)
$(DEBIAN_PKG): deb-clean deb-init deb-deps deb-control deb-scripts deb-cp deb-package arch: $(ARCH_PKG)
rpm: $(RPM_PKG)
ipk: $(IPK_PKG)
tar: tgz
tgz: $(TGZ_PKG)
clean: clean:
@rm -rf tmp/* out/* @rm -rf tmp/* out/*
deb-clean:
@rm -rf $(DEBIAN_DIR) $(DEBIAN_PKG)
deb-init:
@mkdir -p tmp out $(DEBIAN_DIR)
deb-deps: $(CONTROLFILES)
@which dpkg >/dev/null && which dpkg-buildpackage >/dev/null && which dch >/dev/null || { echo "You need essential debian developer tools. Please install them:\nsudo apt-get install build-essential devscripts debhelper"; exit 2; }
deb-control:
@mkdir -p $(DEBIAN_CTRL)
@. lib/zaf.lib.sh; \
. lib/ctrl.lib.sh; \
for p in $(PLUGINS); do \
DEPENDS="$$DEPENDS,$$(zaf_ctrl_get_global_option $$p/control.zaf Depends-dpkg | tr ' ' ',')"; \
done; \
[ "$$ZAF_GITBRANCH" = "master" ] && master=master; \
zaf_far '{ZAF_VERSION}' "$${ZAF_VERSION}$$master" <files/control.template | zaf_far '{ZAF_DEPENDS}' "$$DEPENDS" >$(DEBIAN_CTRL)/control
deb-scripts:
@. lib/zaf.lib.sh; \
. lib/ctrl.lib.sh; \
cat files/postinst.template | \
zaf_far '{PLUGINS}' "$$(for p in $(PLUGINS); do echo $$(basename $$p); done)" | \
zaf_far '{IPLUGINS}' "$$(for p in $(IPLUGINS); do echo $$(basename $$p); done)" | \
zaf_far '{ZAF_LIB_DIR}' "/usr/lib/zaf" >$(DEBIAN_CTRL)/postinst
@chmod +x $(DEBIAN_CTRL)/postinst
@cp files/preinst.template $(DEBIAN_CTRL)/preinst
@chmod +x $(DEBIAN_CTRL)/preinst
@cp files/prerm.template $(DEBIAN_CTRL)/prerm
@chmod +x $(DEBIAN_CTRL)/prerm
deb-cp:
@mkdir -p $(DEBIAN_DIR)
@set -e; INSTALL_PREFIX=$(DEBIAN_DIR) ZAF_DEBUG=$(ZAF_DEBUG) ./install.sh auto $(ZAF_OPTIONS) $(AGENT_OPTIONS)
@. lib/zaf.lib.sh; \
. lib/ctrl.lib.sh; \
for p in $(PLUGINS); do \
plugin=$$(zaf_ctrl_get_global_option $$p/control.zaf Plugin) ; \
mkdir -p $(DEBIAN_DIR)/usr/lib/zaf/prepackaged/$$plugin/; \
cp -R $$p/* $(DEBIAN_DIR)/usr/lib/zaf/prepackaged/$$plugin/; \
done
@cat lib/*lib.sh install.sh >$(DEBIAN_DIR)/usr/lib/zaf/install.sh
@chmod +x $(DEBIAN_DIR)/usr/lib/zaf/install.sh
@rm -rf $(DEBIAN_DIR)/tmp
@cp $(DEBIAN_DIR)/etc/zaf.conf tmp/zaf.conf
@grep -E "$$(echo $(ZAF_EXPORT_OPTS) | tr ' ' '|')=" tmp/zaf.conf >$(DEBIAN_DIR)/etc/zaf.conf
@echo "ZAF_PREPACKAGED_DIR=\"/usr/lib/zaf/prepackaged\"" >>$(DEBIAN_DIR)/etc/zaf.conf
ifneq ($(AGENT_OPTIONS),)
@echo "ZAF_AGENT_OPTIONS=\"$(AGENT_OPTIONS)\"" >>$(DEBIAN_DIR)/etc/zaf.conf
endif
deb-package:
@dpkg-deb -b $(DEBIAN_DIR) $(DEBIAN_PKG)
@echo "\nCheck configuration:"
@cat $(DEBIAN_DIR)/etc/zaf.conf
@echo PLUGINS embedded: $(PLUGINS)
@echo PLUGINS in postinst: $(IPLUGINS)
@echo

199
README.md
View File

@@ -24,56 +24,113 @@ So zaf is here for you :)
* Zabbix agent autoinstallation and autoconfiguration suitable to use in puppet or another tool * Zabbix agent autoinstallation and autoconfiguration suitable to use in puppet or another tool
* OS packaging support * OS packaging support
* Zabbix API support * Zabbix API support
* Zabbix host autoregistration automation
* Zabbix sender and agent glue (send results of agent checks to zabbix sender)
* Zabbix backup support using [zaf](https://macura.cz/node/34)
* Support for wireless neighbours, clients with autodiscovery [iwx module](https://github.com/limosek/zaf-plugins/tree/master/iwx)
* Support for automated import of hosts and items from [CSV](https://github.com/limosek/zaf-plugins/tree/master/csv)
* Support for fail2ban monitoring [fail2ban](https://github.com/limosek/zaf-plugins/tree/master/fail2ban)
* Supoort for booked [booked](https://github.com/limosek/zaf-plugins/tree/master/booked)
## Roadmap
* External items support with automatic configuration of server
## How it works
Zaf installer will do most of actions needed to monitor some specific plugin items. Configuration of plugin is very simple and text readable. Anybody can write its own plugin or make its plugin "zafable". It is enough to create *control.zaf" file. For example, look into https://github.com/limosek/zaf-plugins repository. This is default repository for zaf.
## I want to make my own plugin!
Great! Look into https://github.com/limosek/zaf-plugins repository, look to control files and try to create your own. It is easy! You can contact me for help.
## I want to help with zaf!
Great! I have no time for testing on systems and writing system specific hacks. Next to this, templates should be optimized and tested for basic plugins.
## I love this tool
OK, great, if you love this tool, you can support new development on paypal account *lukas@macura.cz* or Bitcoin address **19Wbr729vei35gUQLcH2ZJGKb8oTVLz44K**.
## Installing Zaf ## Installing Zaf
**Note**: this instructions are for *trunk* version of zaf. For *stable* version, see https://github.com/limosek/zaf/tree/1.3
**Note**: You can find more examples on [my site](https://macura.cz/search/node?keys=zaf)
You need to be root and you must have curl installed on your system. Depending on your system, github certificates may not be available so you have to use *-k* option for curl (insecure). Default installation type is silent. So there will be no questions and everything will be autodetected. This simple command should be used on most systems: You need to be root and you must have curl installed on your system. Depending on your system, github certificates may not be available so you have to use *-k* option for curl (insecure). Default installation type is silent. So there will be no questions and everything will be autodetected. This simple command should be used on most systems:
``` ```
curl -k https://raw.githubusercontent.com/limosek/zaf/1.2/install.sh | sh curl -k https://raw.githubusercontent.com/limosek/zaf/master/install.sh | sh
```
If you have only wget installed:
```
wget --no-check-certificate -O - https://raw.githubusercontent.com/limosek/zaf/master/install.sh | sh
```
If you do not have https support (like openwrt), I made small http mirror of github files which is synchronized each day:
```
wget -O - http://github.macura.cz/zaf/install.sh| ZAF_RAW_URL=http://github.macura.cz/zaf/ ZAF_URL=http://github.macura.cz/zaf/ ZAF_REPO_URL=http://github.macura.cz/zaf-plugins/ sh
``` ```
### Install options and autoconfiguration ### Install options and autoconfiguration
General parameters for install.sh on any system (simplest way how to install) General parameters for install.sh on any system (simplest way how to install)
``` ```
curl -k https://raw.githubusercontent.com/limosek/zaf/1.2/install.sh | \ curl -k https://raw.githubusercontent.com/limosek/zaf/master/install.sh | \
sh -s {auto|interactive|debug-auto|debug-interactive} [Agent-Options] [Zaf-Options] sh -s {auto|interactive|debug-auto|debug-interactive} [Agent-Options] [Server-Options] [Zaf-Options]
``` ```
or use git version: or use git version:
``` ```
git clone https://github.com/limosek/zaf.git; cd zaf; git checkout 1.2 git clone https://github.com/limosek/zaf.git; cd zaf; git checkout master
./install.sh {auto|interactive|debug-auto|debug-interactive} [Agent-Options] [Zaf-Options]
./install.sh {auto|interactive|debug-auto|debug-interactive} [Agent-Options] [Server-Options] [Zaf-Options]
Agent-Options: Z_Option=value [...] Agent-Options: Z_Option=value [...]
Server-Options: S_Option=value [...]
Zaf-Options: ZAF_OPT=value [...] Zaf-Options: ZAF_OPT=value [...]
To unset Agent-Option use Z_Option='' To unset Agent-Option use Z_Option=''
``` ```
So you can pass ANY configuration of your zabbix agent directly to installer prefixing it with *Z_*. Please note that options are *Case Sensitive*! So you can pass ANY configuration of your zabbix agent directly to installer prefixing it with *Z_*. Please note that options are *Case Sensitive*!
Next to this, you can pass ANY zaf config options by *ZAF_* prefix. Interresting ZAF options: Next to this, you can pass ANY zaf config options by *ZAF_* prefix. You can see all interesting ZAF options if you use install interactive command.
``` Interresting ZAF options:
# If we want to use GIT and local GIT repository
ZAF_GIT='1'# Default
# Git repository. Can be your local version Option|Info|Default
ZAF_REPO_GITURL='https://github.com/limosek/zaf-plugins.git' ------|----|-------
ZAF_PKG|Packaging system to use|detect
# Where to install plugins ZAF_OS|Operating system to use|detect
ZAF_PLUGINS_DIR='/usr/lib/zaf/plugins' ZAF_OS_CODENAME|Operating system codename|detect
ZAF_AGENT_PKG|Zabbix agent package|detect
# Plugins can be downloaded from http[s] too ZAF_AGENT_OPTIONS|Zabbix options to set in cfg|empty
ZAF_REPO_URL='https://raw.githubusercontent.com/limosek/zaf-plugins/master/' ZAF_GIT|Git is installed|detect
ZAF_CURL_INSECURE|Insecure curl (accept all certificates)|1
``` ZAF_TMP_DIR|Tmp directory|/tmp/
ZAF_CACHE_DIR|Cache directory|/tmp/zafc
ZAF_LIB_DIR|Libraries directory|/usr/lib/zaf
ZAF_PLUGINS_DIR|Plugins directory|${ZAF_LIB_DIR}/plugins
ZAF_PROXY|http[s] and ftp proxy used by zaf|empty
ZAF_REPO_URL|Plugins http[s] repository|https://raw.githubusercontent.com/limosek/zaf-plugins/master/
ZAF_REPO_DIR|Plugins directory|${ZAF_LIB_DIR}/repo
ZAF_AGENT_CONFIG|Zabbix agent config|/etc/zabbix/zabbix_agentd.conf
ZAF_AGENT_CONFIGD|Zabbix agent config.d|/etc/zabbix/zabbix_agentd.conf.d/
ZAF_AGENT_BIN|Zabbix agent binary|/usr/sbin/zabbix_agentd
ZAF_AGENT_RESTART|Zabbix agent restart cmd|detect
ZAF_SERVER_CONFIG|Zabbix server config|/etc/zabbix/zabbix_server.conf
ZAF_SERVER_CONFIGD|Zabbix server config.d|/etc/zabbix/zabbix_server.conf.d/
ZAF_SERVER_BIN|Zabbix server binary|/usr/sbin/zabbix_server
ZAF_SUDOERSD|Sudo sudoers.d directory|/etc/sudoers.d
ZAF_CROND|Cron.d directory|/etc/cron.d
ZAF_ZBXAPI_URL|Zabbix API url|http://localhost/zabbix/api_jsonrpc.php
ZAF_ZBXAPI_USER|Zabbix API user|zaf
ZAF_ZBXAPI_PASS|Zabbix API password|empty
ZAF_ZBXAPI_AUTHTYPE|Zabbix API authentication type|internal
ZAF_PLUGINS|Plugins to autoinstall|empty
ZAF_ZBXSRV_HOST|Zabbix server hostname|zabbix
ZAF_ZBXSRV_PORT|Zabbix server port|10051
ZAF_HOSTNAME|Hostname of this machine|automatic
Installer will try to autoguess suitable config options for your system. Installer will try to autoguess suitable config options for your system.
Now everything was tested on Debian and OpenWrt. If somebody is interrested in, you can help and test with some rpm specific functions. Remember that on some systems, default zabbix agent config is empty so you *need to* enter essential config options as parameters. Now everything was tested on Debian and OpenWrt. If somebody is interrested in, you can help and test with some rpm specific functions. Remember that on some systems, default zabbix agent config is empty so you *need to* enter essential config options as parameters.
### Example ### Example
Suppose you want to autoinstall agent on clean system. You need only curl installed. Everything else is one-cmd process. Suppose you want to autoinstall agent on clean system. You need only curl installed. Everything else is one-cmd process.
This command will install zaf, install zabbix-agent if necessary and sets zabbix variables on agent to reach server. This command can be automatized by puppet or another deploying system. This command will install zaf, install zabbix-agent if necessary and sets zabbix variables on agent to reach server (Server and ServerActive to zabbix.server.local). This command can be automatized by puppet or another deploying system.
``` ```
curl -k https://raw.githubusercontent.com/limosek/zaf/1.2/install.sh | sh -s auto \ curl -k https://raw.githubusercontent.com/limosek/zaf/master/install.sh | sh -s auto \
Z_Server=zabbix.server.local \ ZAF_ZBXSRV_HOST=zabbix.server.local \
Z_ServerActive=zabbix.server.local \
Z_HostnameItem=system.hostname Z_RefreshActiveChecks=60 \
ZAF_REPO_GITURL="git://gitserver.local" ZAF_REPO_GITURL="git://gitserver.local"
``` ```
@@ -82,16 +139,15 @@ You can make your own deb package with preconfigured option. It is up to you to
``` ```
git clone https://github.com/limosek/zaf.git \ git clone https://github.com/limosek/zaf.git \
&& cd zaf \ && cd zaf \
&& git checkout 1.2 \ && git checkout master \
&& git clone https://github.com/limosek/zaf-plugins.git \ && git clone https://github.com/limosek/zaf-plugins.git \
&& make deb PLUGINS="./zaf-plugins/fsx" IPLUGINS="zaf" ZAF_OPTIONS="ZAF_GIT=0" AGENT_OPTIONS="Z_Server=zabbix.server Z_ServerActive=zabbix.server Z_StartAgents=8" && make deb PLUGINS="./zaf-plugins/fsx" ZAF_PLUGINS="zaf" ZAF_OPTIONS="ZAF_GIT=0 ZAF_ZBXSRV_HOST=zabbix.server.local" AGENT_OPTIONS="Z_StartAgents=8"
sudo dpkg -i out/zaf-1.2.deb sudo dpkg -i out/zaf-1.4master.deb
``` ```
General usage: General usage:
``` ```
make {deb|ipk|rpm} [PLUGINS="/dir/plg1 [/dir2]...] [IPLUGINS="plg1 [plg2]..."] [ZAF_OPTIONS="ZAF_cfg=val ..."] [AGENT_OPTIONS="Z_Server=host ..."] make {deb|ipk|rpm} [ZAF_PLUGINS="plg1 [plg2]" [ZAF_OPTIONS="ZAF_cfg=val ..."] [AGENT_OPTIONS="..."]
PLUGINS are embedded into package. Has to be local directories accessible during build. ZAF_PLUGINS are embedded into package. Has to be local directories accessible during build.
IPLUGINS will be downloaded and installed after package is installed. Can be name or url accessible after package installation.
``` ```
## Zaf plugin ## Zaf plugin
@@ -124,10 +180,9 @@ Cmd: sudo fail2ban-client status $1 | grep "Currently banned:" | grep -o -E "[0-
During plugin installation, zaf will check all dependencies, do install binaries and generates apropriate zabbix.conf.d entries. Look into https://github.com/limosek/zaf-plugins repository for more examples. During plugin installation, zaf will check all dependencies, do install binaries and generates apropriate zabbix.conf.d entries. Look into https://github.com/limosek/zaf-plugins repository for more examples.
## Zaf utility ## Zaf utility
Zaf binary can be installed on any system from openwrt to big system. It has minimal dependencies and is shell based. Is has minimal size (up to 50kb of code). It can be used for installing, removing and testing zaf plugin items. Zaf should be run as root. Zaf binary can be installed on any system from openwrt to big system. It has minimal dependencies and is shell based. Is has minimal size (up to 50kb of code). It can be used for installing, removing and testing zaf plugin items. Zaf has to be configured and installed by root but it can be invoked as regular user.
``` ```
./zaf ./zaf Version 1.4. Please use some of this commands:
./zaf Version 1.2. Please use some of this commands:
./zaf Cmd [ZAF_OPTION=value] [ZAF_CTRL_Option=value] [ZAF_CTRLI_Item_Option=value] ... ./zaf Cmd [ZAF_OPTION=value] [ZAF_CTRL_Option=value] [ZAF_CTRLI_Item_Option=value] ...
Plugin manipulation commands: Plugin manipulation commands:
./zaf update To update repo (not plugins, similar to apt-get update) ./zaf update To update repo (not plugins, similar to apt-get update)
@@ -143,39 +198,33 @@ Plugin info commands:
Plugin diagnostic commands: Plugin diagnostic commands:
./zaf test [plugin[.item]] To test [all] suported items by zabbix_agentd [for plugin] ./zaf test [plugin[.item]] To test [all] suported items by zabbix_agentd [for plugin]
./zaf get [plugin[.item]] To test [all] suported items by zabbix_get [for plugin] ./zaf get [plugin[.item]] To test [all] suported items by zabbix_get [for plugin]
./zaf run [plugin[.item]] To test [all] suported items by directly runing command [for plugin]
./zaf precache [plugin[.item]] To precache [all] suported items ./zaf precache [plugin[.item]] To precache [all] suported items
./zaf itemsh plugin.item To spawn interactive shell in item context (same as UserParameter).
Zabbix API commands: Zabbix API commands:
./zaf api To zabbix API functions. See ./zaf api for more info. ./zaf api To zabbix API functions. See ./zaf api for more info.
Zabbix trapper commands:
./zaf send plugin.item To send result of agent param directly to Zabbix server by zabbix_server.
Zabbix agent registration:
./zaf register [hostname] [metadata] To register hostname on Zabbix server (autoregistration).
Agent config info commands: Agent config info commands:
./zaf userparms See userparms generated from zaf on stdout ./zaf userparms See userparms generated from zaf on stdout
./zaf agent-config Reconfigure zabbix userparms in /etc/zabbix/zabbix_agentd.d ./zaf agent-config [force] Reconfigure zabbix userparms in /etc/zabbix/zabbix_agentd.d
Zaf related commands: Zaf related commands:
./zaf self-upgrade To self-upgrade zaf ./zaf self-upgrade To self-upgrade zaf
./zaf self-remove To self-remove zaf and its config ./zaf self-remove To self-remove zaf and its config
./zaf cache-clean To remove all entries from cache ./zaf cache-clean To remove all entries from cache
./zaf cache-list To show all entries in cache
``` ```
Zaf can even communicate with zabbix server using its API. If you set ZAF_ZBXAPI_URL, ZAF_ZBXAPI_USER and ZAF_ZBXAPI_PASS in /etc/zaf.conf, you can use it: ### Plugin operations
```
./zaf api command [parameters]
get-host-id host Get host id
get-byid-host id [property] Get host property from id. Leave empty property for JSON
get-template-id template Get template id
get-byid-template id [property] Get template property from id. Leave empty property for JSON
get-map-id map Get map id
get-byid-map id [property] Get map property from id. Leave empty property for JSON
get-inventory host [fields] Get inventory fields [or all fields]
export-hosts dir [hg] Backup all hosts [in group hg] (get their config from zabbix and save to dir/hostname.xml)
export-host host Backup host (get config from zabbix to stdout)
import-template {plugin|file} Import template for plugin or from file
export-template name Export template to stdout
export-templates dir Export all templates to dir
```
### Installing plugin #### Installing plugin
To install plugin from common repository. If git is available, local git repo is tried first. If not, remote https repo is tried second. To install plugin from common repository. If git is available, local git repo is tried first. If not, remote https repo is tried second.
``` ```
zaf install zaf zaf install zaf
@@ -190,14 +239,50 @@ zaf install /some/plugin
``` ```
Installer will look into control file, run setup task defined there, fetch binaries and scripts needed for specific plugin and test system dependencies for that plugin. If everything is OK, zaf_plugin.conf is created in zabbix_agentd.d conf directory and userparameters are automaticaly added. Installer will look into control file, run setup task defined there, fetch binaries and scripts needed for specific plugin and test system dependencies for that plugin. If everything is OK, zaf_plugin.conf is created in zabbix_agentd.d conf directory and userparameters are automaticaly added.
## How it works #### Plugin parameters
Zaf installer will do most of actions needed to monitor some specific plugin items. Configuration of plugin is very simple and text readable. Anybody can write its own plugin or make its plugin "zafable". It is enough to create *control.zaf" file. For example, look into https://github.com/limosek/zaf-plugins repository. This is default repository for zaf. Plugin can have some global parameters. For example url of local server to check. See booked plugin. In that case, you have to specify parameters before use.
To set parameters by environment:
```
zaf install booked ZAF_booked_url=http://booked.server/api ZAF_booked_username=user
```
To set parameters later:
```
zaf plugin-set booked url http://booked.server/api
zaf plugin-set booked username user
```
Plugin parameters are available as environment variables in shell script/binary run by agent. You can simulate this environment by
```
zaf itemsh booked.num_reservations
```
Interactive shell will be spawn and you can test your commands or scripts in same way how zabbix agent would do it. Use exit command or ctrl-D to get back.
#### Run plugin subcommand
If plugin is capable of runing subcommand (for example csv plugin), it can be called directly
```
zaf csv send
```
### Agent tests
#### To test result of item (using zabbix_agent -t)
```
zaf test plugin.item[parameters]
```
#### To test result of item (using zabbix_get)
```
zaf test plugin.item[parameters]
```
#### To get result of item directly to stdout
```
zaf run plugin.item[parameters]
```
## I want to make my own plugin!
Great! Look into https://github.com/limosek/zaf-plugins repository, look to control files and try to create your own. It is easy! You can contact me for help.
## I want to help with zaf!
Great! I have no time for testing on systems and writing system specific hacks. Next to this, templates should be optimized and tested for basic plugins.

22
arch.mk Normal file
View File

@@ -0,0 +1,22 @@
# Arch linux specific definitions
ARCH_DIR=tmp/archlinux
ifeq ($(ARCH_PKG),)
ARCH_PKG=$(shell . lib/zaf.lib.sh; echo out/zaf-$$ZAF_VERSION.arch)
endif
$(ARCH_PKG): clean arch-init arch-build
arch-init:
@mkdir -p tmp out $(ARCH_DIR)
@. lib/zaf.lib.sh; \
. lib/ctrl.lib.sh; \
cat files/archlinux/PKGBUILD | zaf_far '{PLUGINS}' "$(PLUGINS)" | zaf_far "{IPLUGINS}" "$(IPLUGINS)" | \
zaf_far "{ZAF_OPTIONS}" "$(ZAF_OPTIONS)" | zaf_far "{AGENT_OPTIONS}" "$(AGENT_OPTIONS)" \
>$(ARCH_DIR)/PKGBUILD
arch-build:
@cd $(ARCH_DIR) && makepkg -f

57
deb.mk Normal file
View File

@@ -0,0 +1,57 @@
# Debian specific config
DEBIAN_DIR=tmp/deb
DEBIAN_CTRL=$(DEBIAN_DIR)/DEBIAN
ifeq ($(DEBIAN_PKG),)
DEBIAN_PKG=$(shell . lib/zaf.lib.sh; echo out/zaf-$$ZAF_VERSION.deb)
endif
$(DEBIAN_PKG): clean deb-init deb-deps deb-control deb-scripts deb-cp deb-package
deb-init:
@mkdir -p tmp out $(DEBIAN_DIR)
deb-deps: $(CONTROLFILES)
@which dpkg >/dev/null && which dpkg-buildpackage >/dev/null && which dch >/dev/null || { echo "You need essential debian developer tools. Please install them:\nsudo apt-get install build-essential devscripts debhelper"; exit 2; }
deb-control:
@mkdir -p $(DEBIAN_CTRL)
@. lib/zaf.lib.sh; \
. lib/ctrl.lib.sh; \
for p in $(PLUGINS); do \
DEPENDS="$$DEPENDS,$$(zaf_ctrl_get_global_option $$p/control.zaf Depends-dpkg | tr ' ' ',')"; \
done; \
[ "$$ZAF_GITBRANCH" = "master" ] && master=master; \
zaf_far '{ZAF_VERSION}' "$${ZAF_VERSION}$$master" <files/debian/control.template | zaf_far '{ZAF_DEPENDS}' "$$DEPENDS" >$(DEBIAN_CTRL)/control
deb-scripts:
@. lib/zaf.lib.sh; \
. lib/ctrl.lib.sh; \
cat files/debian/postinst.template >$(DEBIAN_CTRL)/postinst
@chmod +x $(DEBIAN_CTRL)/postinst
@cp files/debian/preinst.template $(DEBIAN_CTRL)/preinst
@chmod +x $(DEBIAN_CTRL)/preinst
@cp files/debian/prerm.template $(DEBIAN_CTRL)/prerm
@chmod +x $(DEBIAN_CTRL)/prerm
deb-cp:
@mkdir -p $(DEBIAN_DIR)
@set -e; INSTALL_PREFIX=$(DEBIAN_DIR) ZAF_DEBUG=$(ZAF_DEBUG) ./install.sh auto $(ZAF_OPTIONS) ZAF_PLUGINS="$(ZAF_PLUGINS)" $(AGENT_OPTIONS)
@cat lib/*lib.sh install.sh >$(DEBIAN_DIR)/usr/lib/zaf/install.sh
@chmod +x $(DEBIAN_DIR)/usr/lib/zaf/install.sh
@rm -rf $(DEBIAN_DIR)/tmp
@cp $(DEBIAN_DIR)/etc/zaf.conf tmp/zaf.conf
@grep -E "$$(echo $(ZAF_EXPORT_OPTS) | tr ' ' '|')=" tmp/zaf.conf >$(DEBIAN_DIR)/etc/zaf.conf
ifneq ($(AGENT_OPTIONS),)
@echo "ZAF_AGENT_OPTIONS=\"$(AGENT_OPTIONS)\"" >>$(DEBIAN_DIR)/etc/zaf.conf
endif
deb-package:
@dpkg-deb -b $(DEBIAN_DIR) $(DEBIAN_PKG)
@echo "\nCheck configuration:"
@cat $(DEBIAN_DIR)/etc/zaf.conf
@echo PLUGINS embedded: $(ZAF_PLUGINS)
@echo

39
files/archlinux/PKGBUILD Normal file
View File

@@ -0,0 +1,39 @@
pkgname="zaf-git"
pkgver=${PKGVER:-autogenerated}
pkgrel=${PKGREL:-1}
pkgdesc="zabbix agent framework - a cli tool for zabbix"
arch=("i686" "x86_64")
license=("GPL")
depends=(
"lsb-release"
"git"
)
backup=(
"etc/zaf.conf"
)
source=(
"zaf-git::git://github.com/limosek/zaf#branch=master"
)
md5sums=("SKIP")
pkgver() {
cd "$srcdir/$pkgname"
local date=$(git log -1 --format="%cd" --date=short | sed s/-//g)
local count=$(git rev-list --count HEAD)
local commit=$(git rev-parse --short HEAD)
echo "$date.${count}_$commit"
}
build() {
cd "$srcdir/$pkgname"
:
}
package() {
cd "$srcdir/$pkgname"
INSTALL_PREFIX="$pkgdir" \
./install.sh auto {ZAF_OPTIONS} {AGENT_OPTIONS}
}

View File

@@ -0,0 +1,10 @@
#!/bin/sh
case $1 in
configure)
zaf agent-config
;;
esac
true

View File

@@ -1,22 +0,0 @@
#!/bin/sh
case $1 in
configure)
if [ -f /usr/lib/zaf/install.sh ] && [ -f /etc/zaf.conf ] && [ -f /usr/lib/zaf/zaf.lib.sh ] && which zaf >/dev/null; then
. /etc/zaf.conf
. /usr/lib/zaf/zaf.lib.sh
. /usr/lib/zaf/os.lib.sh
. /usr/lib/zaf/ctrl.lib.sh
cd /usr/lib/zaf && /usr/lib/zaf/install.sh reconf
[ -n "{PLUGINS}" ] && for p in {PLUGINS}; do
if ! zaf_is_plugin $p;then
zaf install $ZAF_PREPACKAGED_DIR/$p;
fi
done
[ -n "{IPLUGINS}" ] && zaf reinstall {IPLUGINS}
fi
;;
esac
true

View File

@@ -1,18 +1,45 @@
#!/bin/sh #!/bin/sh
[ -z "$ZAF_DEBUG" ] && ZAF_DEBUG=1
if [ -z "$ZAF_URL" ]; then
# Runing as standalone install.sh. We have to download rest of files first.
ZAF_URL="https://github.com/limosek/zaf/"
fi
if [ -z "$ZAF_RAW_URL" ]; then
ZAF_RAW_URL="https://raw.githubusercontent.com/limosek/zaf"
fi
[ -z "$ZAF_GITBRANCH" ] && ZAF_GITBRANCH=master
############### Functions ############### Functions
# Lite version of zaf_fetch_url, full version will be loaded later # Lite version of zaf_fetch_url, full version will be loaded later
zaf_fetch_url(){ zaf_fetch_url(){
echo curl -f -k -s -L -o - "$1" >&2; if zaf_which curl >/dev/null 2>/dev/null; then
curl -f -k -s -L -o - "$1" echo curl -f -k -s -L -o - "$1" >&2;
curl -f -k -s -L -o - "$1"
else
wget --no-check-certificate -O - "$1"
fi
}
# Lite version of zaf_which, full version will be loaded later
zaf_which() {
if which >/dev/null 2>/dev/null; then
which "$1"
else
for i in /bin /sbin /usr/bin /usr/sbin /usr/local/bin /usr/local/sbin; do
[ -x $i/$1 ] && { echo $i/$1; return; }
done
return 1
fi
} }
# Lite version of zaf_err, full version will be loaded later # Lite version of zaf_err, full version will be loaded later
zaf_err() { zaf_err() {
logger ${ZAF_LOG_STDERR} -p user.err -t zaf-error -- $@ logger ${ZAF_LOG_STDERR} -p user.err -t zaf-error -- $@
logger ${ZAF_LOG_STDERR} -p user.err -t zaf-error "Exiting with error!" logger ${ZAF_LOG_STDERR} -p user.err -t zaf-error "Exiting with error!"
exit 1 exit 1
} }
# Download tgz and extract to tmpdir # Download tgz and extract to tmpdir
@@ -31,12 +58,13 @@ zaf_download_files() {
zaf_get_option(){ zaf_get_option(){
local opt local opt
eval opt=\$C_$1 ZAF_HELP_OPTS="$ZAF_HELP_OPTS\n$1 $2 [$3]"
eval opt=\$C_$1
if [ -n "$opt" ]; then if [ -n "$opt" ]; then
eval "$1='$opt'" eval "$1='$opt'"
zaf_dbg "Got '$2' <$1> from CLI: $opt" zaf_dbg "Got '$2' <$1> from CLI: $opt"
return return
fi fi
eval opt=\$$1 eval opt=\$$1
if [ -n "$opt" ] && ! [ "$4" = "user" ]; then if [ -n "$opt" ] && ! [ "$4" = "user" ]; then
eval "$1='$opt'" eval "$1='$opt'"
@@ -74,54 +102,73 @@ zaf_set_option(){
fi fi
} }
# Set config option in zabbix agent config file # Set config option in zabbix config file
# $1 option # $1 config file
# $2 value # $2 option
zaf_set_agent_option() { # $3 value
local option="$1" zaf_set_zabbix_option() {
local value="$2" local cfgfile="$1"
if grep -q ^$option\= $ZAF_AGENT_CONFIG; then local option="$2"
zaf_dbg "Setting option $option in $ZAF_AGENT_CONFIG." local value="$3"
sed -i "s/$option=\(.*\)/$option=$2/" $ZAF_AGENT_CONFIG if grep -q ^$option\= $cfgfile; then
zaf_dbg "Setting Zabbix agent option $option in $cfgfile to $3."
sed -i "s/$option=\(.*\)/$option=$value/" $cfgfile
else else
zaf_move_agent_option "$1" "$2" zaf_move_zabbix_option "$1" "$2" "$3"
fi fi
} }
# Unset config option in zabbix agent config file # Get config option from zabbix config file
# $1 option # $1 config file
zaf_unset_agent_option() { # $2 option
local option="$1" zaf_get_zabbix_option() {
local value="$2" local cfgfile="$1"
if grep -q ^$option\= $ZAF_AGENT_CONFIG; then local option="$2"
zaf_dbg "Unsetting option $option in $ZAF_AGENT_CONFIG." grep ^$option\= $cfgfile | cut -d '=' -f 2-;
sed -i "s/$option=\(.*\)/#$option=$2/" $ZAF_AGENT_CONFIG }
# Unset config option in zabbix config file
# $1 config file
# $2 option
zaf_unset_zabbix_option() {
local cfgfile="$1"
local option="$2"
local value="$3"
if grep -q ^$option\= $cfgfile; then
zaf_dbg "Unsetting option $option in $cfgfile."
sed -i "s/$option=\(.*\)/#$option=$2/" $cfgfile
fi fi
} }
# Add config option in zabbix agent config file # Add config option in zabbix config file
# $1 option # $1 config file
# $2 value # $2 option
zaf_add_agent_option() { # $3 value
local option="$1" zaf_add_zabbix_option() {
local value="$2" local cfgfile="$1"
if ! grep -q "^$1=$2" $ZAF_AGENT_CONFIG; then local option="$2"
zaf_dbg "Adding option $option to $ZAF_AGENT_CONFIG." local value="$3"
echo "$option=$value" >>$ZAF_AGENT_CONFIG if ! grep -q "^$option=$value" $cfgfile; then
zaf_dbg "Adding option $option to $cfgfile."
echo "$option=$value" >>$cfgfile
fi fi
} }
# Move config option fron zabbix agent config file to zaf options file and set value # Move config option fron zabbix config file to zaf options file and set value
# $1 option # $1 config file
# $2 value # $2 options file
zaf_move_agent_option() { # $3 option
local option="$1" # $4 value
local value="$2" zaf_move_zabbix_option() {
if grep -q ^$option\= $ZAF_AGENT_CONFIG; then local cfgfile="$1"
zaf_dbg "Moving option $option from $ZAF_AGENT_CONFIG to ." local optsfile="$2"
sed -i "s/$option=(.*)/$option=$2/" $ZAF_AGENT_CONFIG local option="$3"
local value="$4"
if grep -q ^$option\= $cfgfile; then
zaf_dbg "Moving option $option from $cfgfile to $optsfile."
sed -i "s/$option=(.*)/$option=$value/" $cfgfile
fi fi
[ -n "$value" ] && echo "$option=$value" >> "$ZAF_AGENT_CONFIGD/zaf_options.conf" [ -n "$value" ] && echo "$option=$value" >> "$optsfile"
} }
# Automaticaly configure agent if supported # Automaticaly configure agent if supported
@@ -131,32 +178,75 @@ zaf_configure_agent() {
local option local option
local value local value
local options local options
local changes
local aparams
zaf_install_dir "$ZAF_AGENT_CONFIGD" zaf_install_dir "$ZAF_AGENT_CONFIGD"
echo -n >"$ZAF_AGENT_CONFIGD/zaf_options.conf" || zaf_err "Cannot access $ZAF_AGENT_CONFIGD/zaf_options.conf" echo -n >"$ZAF_AGENT_CONFIGD/zaf_options.conf" || zaf_err "Cannot access $ZAF_AGENT_CONFIGD/zaf_options.conf"
! [ -f "$ZAF_AGENT_CONFIG" ] && zaf_install "$ZAF_AGENT_CONFIG" ! [ -f "$ZAF_AGENT_CONFIG" ] && zaf_install "$ZAF_AGENT_CONFIG"
for pair in "$@"; do if [ -n "$ZAF_ZBXSRV_HOST" ]; then
aparms="Z_Server=$ZAF_ZBXSRV_HOST,localhost Z_ServerActive=$ZAF_ZBXSRV_HOST"
else
aparms=""
fi
if [ -n "$ZAF_HOSTNAME" ]; then
aparms="$aparms Z_Hostname=$ZAF_HOSTNAME"
else
aparms="$aparms Z_HostnameItem=system.hostname Z_Hostname="
zaf_dbg "Using hostname as Hostname item for Zabbix"
fi
for pair in $aparms "$@"; do
echo $pair | grep -q '^Z\_' || continue # Skip non Z_ vars echo $pair | grep -q '^Z\_' || continue # Skip non Z_ vars
option=$(echo $pair|cut -d '=' -f 1|cut -d '_' -f 2) option=$(echo $pair|cut -d '=' -f 1|cut -d '_' -f 2)
value=$(echo $pair|cut -d '=' -f 2-) value=$(echo $pair|cut -d '=' -f 2-)
if [ -n "$value" ]; then if [ -n "$value" ]; then
zaf_set_agent_option "$option" "$value" zaf_set_zabbix_option "$ZAF_AGENT_CONFIG" "$option" "$value"
else else
zaf_unset_agent_option "$option" zaf_unset_zabbix_option "$ZAF_AGENT_CONFIG" "$option"
fi fi
options="$options Z_$option=$value" echo $options |grep -vq "Z_$option=" && options="$options Z_$option=$value"
changes=1
done done
zaf_set_option ZAF_AGENT_OPTIONS "${options}" zaf_set_option ZAF_AGENT_OPTIONS "${options}"
[ -n "$changes" ] # Return false if no changes
} }
# Automaticaly configure server if supported
# Parameters are in format S_zabbixconfvar=value
zaf_configure_server() {
local pair
local option
local value
local options
local changes
zaf_install_dir "$ZAF_SERVER_CONFIGD"
echo -n >"$ZAF_SERVER_CONFIGD/zaf_options.conf" || zaf_err "Cannot access $ZAF_SERVER_CONFIGD/zaf_options.conf"
for pair in "$@"; do
echo $pair | grep -q '^S\_' || continue # Skip non S_ vars
option=$(echo $pair|cut -d '=' -f 1|cut -d '_' -f 2)
value=$(echo $pair|cut -d '=' -f 2-)
if [ -n "$value" ]; then
zaf_set_zabbix_option "$ZAF_SERVER_CONFIG" "$option" "$value"
else
zaf_unset_zabbix_option "$ZAF_SERVER_CONFIG" "$option"
fi
options="$options S_$option=$value"
changes=1
done
zaf_set_option ZAF_SERVER_OPTIONS "${options}"
[ -n "$changes" ] # Return false if no changes
}
zaf_preconfigure(){ zaf_preconfigure(){
zaf_detect_system [ -z "$ZAF_OS" ] && zaf_detect_system
zaf_os_specific zaf_configure_os zaf_os_specific zaf_preconfigure_os
if ! zaf_is_root; then if ! zaf_is_root; then
[ -z "$INSTALL_PREFIX" ] && zaf_err "We are not root. Use INSTALL_PREFIX or become root." [ -z "$INSTALL_PREFIX" ] && zaf_err "We are not root. Use INSTALL_PREFIX or become root."
else else
[ "$1" != "reconf" ] && zaf_os_specific zaf_check_deps zaf && zaf_err "Zaf is installed as system package. Cannot install." [ "$1" != "reconf" ] && zaf_os_specific zaf_check_deps zaf && zaf_err "Zaf is installed as system package. Cannot install."
fi fi
} }
zaf_configure(){ zaf_configure(){
@@ -173,38 +263,52 @@ zaf_configure(){
fi fi
fi fi
fi fi
if which git >/dev/null; then if [ -z "$ZAF_GIT" ]; then
ZAF_GIT=1 if zaf_which git >/dev/null; then
else ZAF_GIT=1
ZAF_GIT=0 else
ZAF_GIT=0
fi
fi fi
zaf_get_option ZAF_GIT "Git is installed" "$ZAF_GIT" "$INSTALL_MODE" zaf_get_option ZAF_GIT "Git is installed" "$ZAF_GIT" "$INSTALL_MODE"
zaf_get_option ZAF_CURL_INSECURE "Insecure curl (accept all certificates)" "1" "$INSTALL_MODE" zaf_get_option ZAF_CURL_INSECURE "Insecure curl (accept all certificates)" "1" "$INSTALL_MODE"
zaf_get_option ZAF_TMP_DIR "Tmp directory" "/tmp/" "$INSTALL_MODE" zaf_get_option ZAF_TMP_DIR "Tmp directory" "/tmp/" "$INSTALL_MODE"
zaf_get_option ZAF_CACHE_DIR "Cache directory" "/tmp/zafc" "$INSTALL_MODE" zaf_get_option ZAF_CACHE_DIR "Cache directory" "/tmp/zafc" "$INSTALL_MODE"
zaf_get_option ZAF_LIB_DIR "Libraries directory" "/usr/lib/zaf" "$INSTALL_MODE" zaf_get_option ZAF_LIB_DIR "Libraries directory" "/usr/lib/zaf" "$INSTALL_MODE"
zaf_get_option ZAF_BIN_DIR "Directory to put binaries" "/usr/bin" "$INSTALL_MODE" zaf_get_option ZAF_BIN_DIR "Directory to put binaries" "/usr/bin" "$INSTALL_MODE"
zaf_get_option ZAF_PLUGINS_DIR "Plugins directory" "${ZAF_LIB_DIR}/plugins" "$INSTALL_MODE" zaf_get_option ZAF_PLUGINS_DIR "Plugins directory" "${ZAF_LIB_DIR}/plugins" "$INSTALL_MODE"
[ "${ZAF_GIT}" = 1 ] && zaf_get_option ZAF_REPO_GITURL "Git plugins repository" "https://github.com/limosek/zaf-plugins.git" "$INSTALL_MODE" [ "${ZAF_GIT}" = 1 ] && zaf_get_option ZAF_REPO_GITURL "Git plugins repository" "https://github.com/limosek/zaf-plugins.git" "$INSTALL_MODE"
zaf_get_option ZAF_PROXY "http proxy used by zaf" "" "$INSTALL_MODE"
zaf_get_option ZAF_REPO_URL "Plugins http[s] repository" "https://raw.githubusercontent.com/limosek/zaf-plugins/master/" "$INSTALL_MODE" zaf_get_option ZAF_REPO_URL "Plugins http[s] repository" "https://raw.githubusercontent.com/limosek/zaf-plugins/master/" "$INSTALL_MODE"
zaf_get_option ZAF_REPO_DIR "Plugins directory" "${ZAF_LIB_DIR}/repo" "$INSTALL_MODE" zaf_get_option ZAF_REPO_DIR "Plugins directory" "${ZAF_LIB_DIR}/repo" "$INSTALL_MODE"
zaf_get_option ZAF_AGENT_CONFIG "Zabbix agent config" "/etc/zabbix/zabbix_agentd.conf" "$INSTALL_MODE" zaf_get_option ZAF_AGENT_CONFIG "Zabbix agent config" "/etc/zabbix/zabbix_agentd.conf" "$INSTALL_MODE"
! [ -d "${ZAF_AGENT_CONFIGD}" ] && [ -d "/etc/zabbix/zabbix_agentd.d" ] && ZAF_AGENT_CONFIGD="/etc/zabbix/zabbix_agentd.d" [ -z "${ZAF_AGENT_CONFIGD}" ] && ! [ -d "${ZAF_AGENT_CONFIGD}" ] && [ -d "/etc/zabbix/zabbix_agentd.d" ] && ZAF_AGENT_CONFIGD="/etc/zabbix/zabbix_agentd.d"
zaf_get_option ZAF_AGENT_CONFIGD "Zabbix agent config.d" "/etc/zabbix/zabbix_agentd.conf.d/" "$INSTALL_MODE" zaf_get_option ZAF_AGENT_CONFIGD "Zabbix agent config.d" "/etc/zabbix/zabbix_agentd.conf.d/" "$INSTALL_MODE"
zaf_get_option ZAF_AGENT_BIN "Zabbix agent binary" "/usr/sbin/zabbix_agentd" "$INSTALL_MODE" zaf_get_option ZAF_AGENT_BIN "Zabbix agent binary" "/usr/sbin/zabbix_agentd" "$INSTALL_MODE"
zaf_get_option ZAF_AGENT_RESTART "Zabbix agent restart cmd" "service zabbix-agent restart" "$INSTALL_MODE" zaf_get_option ZAF_AGENT_RESTART "Zabbix agent restart cmd" "service zabbix-agent restart" "$INSTALL_MODE"
zaf_get_option ZAF_ZBXSRV_HOST "Zabbix server hostname" "zabbix" "$INSTALL_MODE"
zaf_get_option ZAF_ZBXSRV_PORT "Zabbix server port" "10051" "$INSTALL_MODE"
zaf_get_option ZAF_SERVER_CONFIG "Zabbix server config" "/etc/zabbix/zabbix_server.conf" "$INSTALL_MODE"
[ -z "${ZAF_SERVER_CONFIGD}" ] && ! [ -d "${ZAF_SERVER_CONFIGD}" ] && [ -d "/etc/zabbix/zabbix_server.d" ] && ZAF_SERVER_CONFIGD="/etc/zabbix/zabbix_server.d"
zaf_get_option ZAF_SERVER_CONFIGD "Zabbix server config.d" "/etc/zabbix/zabbix_server.conf.d/" "$INSTALL_MODE"
zaf_get_option ZAF_SERVER_BIN "Zabbix server binary" "/usr/sbin/zabbix_server" "$INSTALL_MODE"
zaf_get_option ZAF_HOSTNAME "Hostname of this machine" "" "$INSTALL_MODE"
zaf_get_option ZAF_SUDOERSD "Sudo sudoers.d directory" "/etc/sudoers.d" "$INSTALL_MODE" zaf_get_option ZAF_SUDOERSD "Sudo sudoers.d directory" "/etc/sudoers.d" "$INSTALL_MODE"
zaf_get_option ZAF_CROND "Cron.d directory" "/etc/cron.d" "$INSTALL_MODE" zaf_get_option ZAF_CROND "Cron.d directory" "/etc/cron.d" "$INSTALL_MODE"
zaf_get_option ZAF_ZBXAPI_URL "Zabbix API url" "http://localhost/zabbix/api_jsonrpc.php" "$INSTALL_MODE" zaf_get_option ZAF_ZBXAPI_URL "Zabbix API url" "http://localhost/zabbix/api_jsonrpc.php" "$INSTALL_MODE"
zaf_get_option ZAF_ZBXAPI_USER "Zabbix API user" "zaf" "$INSTALL_MODE" zaf_get_option ZAF_ZBXAPI_USER "Zabbix API user" "zaf" "$INSTALL_MODE"
zaf_get_option ZAF_ZBXAPI_PASS "Zabbix API password" "" "$INSTALL_MODE" zaf_get_option ZAF_ZBXAPI_PASS "Zabbix API password" "" "$INSTALL_MODE"
zaf_get_option ZAF_ZBXAPI_AUTHTYPE "Zabbix API authentication type" "internal" "$INSTALL_MODE" zaf_get_option ZAF_ZBXAPI_AUTHTYPE "Zabbix API authentication type" "internal" "$INSTALL_MODE"
zaf_get_option ZAF_PLUGINS "Plugins to autoinstall" "" "$INSTALL_MODE"
if zaf_is_root && ! [ -x $ZAF_AGENT_BIN ]; then if zaf_is_root && ! [ -x $ZAF_AGENT_BIN ]; then
zaf_err "Zabbix agent ($ZAF_AGENT_BIN) not installed? Use ZAF_AGENT_BIN env variable to specify location. Exiting." zaf_err "Zabbix agent ($ZAF_AGENT_BIN) not installed? Use ZAF_AGENT_BIN env variable to specify location. Exiting."
fi fi
[ -n "$INSTALL_PREFIX" ] && zaf_install_dir "/etc" [ -n "$INSTALL_PREFIX" ] && zaf_install_dir "/etc"
if ! [ -f "${ZAF_CFG_FILE}" ]; then if ! [ -f "${ZAF_CFG_FILE}" ]; then
touch "${ZAF_CFG_FILE}" || zaf_err "No permissions to ${ZAF_CFG_FILE}" touch "${ZAF_CFG_FILE}" || zaf_err "No permissions to ${ZAF_CFG_FILE}"
fi fi
@@ -218,9 +322,10 @@ zaf_configure(){
zaf_set_option ZAF_TMP_DIR "$ZAF_TMP_DIR" zaf_set_option ZAF_TMP_DIR "$ZAF_TMP_DIR"
zaf_set_option ZAF_CACHE_DIR "$ZAF_CACHE_DIR" zaf_set_option ZAF_CACHE_DIR "$ZAF_CACHE_DIR"
zaf_set_option ZAF_LIB_DIR "$ZAF_LIB_DIR" zaf_set_option ZAF_LIB_DIR "$ZAF_LIB_DIR"
zaf_set_option ZAF_BIN_DIR "$ZAF_BIN_DIR" zaf_set_option ZAF_BIN_DIR "$ZAF_BIN_DIR"
zaf_set_option ZAF_PLUGINS_DIR "$ZAF_PLUGINS_DIR" zaf_set_option ZAF_PLUGINS_DIR "$ZAF_PLUGINS_DIR"
zaf_set_option ZAF_REPO_URL "$ZAF_REPO_URL" zaf_set_option ZAF_REPO_URL "$ZAF_REPO_URL"
zaf_set_option ZAF_PROXY "$ZAF_PROXY"
[ "${ZAF_GIT}" = 1 ] && zaf_set_option ZAF_REPO_GITURL "$ZAF_REPO_GITURL" [ "${ZAF_GIT}" = 1 ] && zaf_set_option ZAF_REPO_GITURL "$ZAF_REPO_GITURL"
zaf_set_option ZAF_REPO_DIR "$ZAF_REPO_DIR" zaf_set_option ZAF_REPO_DIR "$ZAF_REPO_DIR"
zaf_set_option ZAF_AGENT_CONFIG "$ZAF_AGENT_CONFIG" zaf_set_option ZAF_AGENT_CONFIG "$ZAF_AGENT_CONFIG"
@@ -230,17 +335,40 @@ zaf_configure(){
zaf_set_option ZAF_FILES_GID "$ZAF_FILES_GID" zaf_set_option ZAF_FILES_GID "$ZAF_FILES_GID"
zaf_set_option ZAF_FILES_UMASK "$ZAF_FILES_UMASK" zaf_set_option ZAF_FILES_UMASK "$ZAF_FILES_UMASK"
zaf_set_option ZAF_AGENT_RESTART "$ZAF_AGENT_RESTART" zaf_set_option ZAF_AGENT_RESTART "$ZAF_AGENT_RESTART"
zaf_set_option ZAF_ZBXSRV_HOST "$ZAF_ZBXSRV_HOST"
zaf_set_option ZAF_ZBXSRV_PORT "$ZAF_ZBXSRV_PORT"
zaf_set_option ZAF_HOSTNAME "$ZAF_HOSTNAME"
if [ -x "$ZAF_SERVER_BIN" ]; then
zaf_set_option ZAF_SERVER_CONFIG "$ZAF_SERVER_CONFIG"
zaf_set_option ZAF_SERVER_CONFIGD "$ZAF_SERVER_CONFIGD"
zaf_set_option ZAF_SERVER_EXTSCRIPTS "$(zaf_get_zabbix_option $ZAF_SERVER_CONFIG ExternalScripts)"
zaf_set_option ZAF_SERVER_BIN "$ZAF_SERVER_BIN"
else
zaf_set_option ZAF_SERVER_CONFIG ""
zaf_set_option ZAF_SERVER_BIN ""
zaf_set_option ZAF_SERVER_CONFIGD ""
zaf_set_option ZAF_SERVER_EXTSCRIPTS ""
fi
zaf_set_option ZAF_SUDOERSD "$ZAF_SUDOERSD" zaf_set_option ZAF_SUDOERSD "$ZAF_SUDOERSD"
zaf_set_option ZAF_CROND "$ZAF_CROND" zaf_set_option ZAF_CROND "$ZAF_CROND"
zaf_set_option ZAF_ZBXAPI_URL "$ZAF_ZBXAPI_URL" zaf_set_option ZAF_ZBXAPI_URL "$ZAF_ZBXAPI_URL"
zaf_set_option ZAF_ZBXAPI_USER "$ZAF_ZBXAPI_USER" zaf_set_option ZAF_ZBXAPI_USER "$ZAF_ZBXAPI_USER"
zaf_set_option ZAF_ZBXAPI_PASS "$ZAF_ZBXAPI_PASS" zaf_set_option ZAF_ZBXAPI_PASS "$ZAF_ZBXAPI_PASS"
zaf_set_option ZAF_ZBXAPI_AUTHTYPE "$ZAF_ZBXAPI_AUTHTYPE" zaf_set_option ZAF_ZBXAPI_AUTHTYPE "$ZAF_ZBXAPI_AUTHTYPE"
[ -n "$ZAF_PREPACKAGED_DIR" ] && zaf_set_option ZAF_PREPACKAGED_DIR "$ZAF_PREPACKAGED_DIR" if [ -n "$ZAF_PLUGINS" ]; then
for p in $(echo $ZAF_PLUGINS | tr ',' ' '); do
zaf_install_plugin $p
done
fi
if zaf_is_root; then if zaf_is_root; then
zaf_configure_agent $ZAF_AGENT_OPTIONS "$@" zaf_configure_agent $ZAF_AGENT_OPTIONS "$@"
zaf_add_agent_option "Include" "$ZAF_AGENT_CONFIGD" zaf_add_zabbix_option "$ZAF_AGENT_CONFIG" "Include" "$ZAF_AGENT_CONFIGD"
if [ -f "$ZAF_SERVER_BIN" ]; then
zaf_configure_server $ZAF_SERVER_OPTIONS "$@" && zaf_add_zabbix_option "$ZAF_SERVER_CONFIG" "Include" "$ZAF_SERVER_CONFIGD"
else
zaf_wrn "Skipping server config. Zabbix server binary '$ZAF_SERVER_BIN' not found."
fi
fi fi
if ! [ -d $ZAF_CACHE_DIR ]; then if ! [ -d $ZAF_CACHE_DIR ]; then
@@ -257,37 +385,38 @@ zaf_configure(){
zaf_install_all() { zaf_install_all() {
zaf_install_dir ${ZAF_LIB_DIR} zaf_install_dir ${ZAF_LIB_DIR}
for i in lib/zaf.lib.sh lib/plugin.lib.sh lib/os.lib.sh lib/ctrl.lib.sh lib/cache.lib.sh lib/zbxapi.lib.sh lib/JSON.sh README.md; do for i in lib/zaf.lib.sh lib/plugin.lib.sh lib/os.lib.sh lib/ctrl.lib.sh lib/cache.lib.sh lib/zbxapi.lib.sh lib/JSON.sh; do
zaf_install $i ${ZAF_LIB_DIR}/ || zaf_err "Error installing $i" zaf_install $i ${ZAF_LIB_DIR}/
done done
for i in lib/zaflock lib/zafcache lib/preload.sh; do for i in lib/zaflock lib/zafcache lib/preload.sh lib/zafret; do
zaf_install_bin $i ${ZAF_LIB_DIR}/ || zaf_err "Error installing $i" zaf_install_bin $i ${ZAF_LIB_DIR}/
done done
zaf_install_dir ${ZAF_BIN_DIR} zaf_install_dir ${ZAF_BIN_DIR}
for i in zaf; do for i in zaf; do
zaf_install_bin $i ${ZAF_BIN_DIR}/ || zaf_err "Error installing $i" zaf_install_bin $i ${ZAF_BIN_DIR}/
done done
zaf_install_dir ${ZAF_PLUGINS_DIR} zaf_install_dir ${ZAF_PLUGINS_DIR}
zaf_install_dir ${ZAF_PLUGINS_DIR} zaf_install_dir ${ZAF_PLUGINS_DIR}
zaf_install_dir ${ZAF_BIN_DIR} zaf_install_dir ${ZAF_BIN_DIR}
} }
zaf_postconfigure() { zaf_postconfigure() {
if zaf_is_root; then if zaf_is_root; then
${INSTALL_PREFIX}/${ZAF_BIN_DIR}/zaf cache-clean ${INSTALL_PREFIX}/${ZAF_BIN_DIR}/zaf cache-clean
[ "${ZAF_GIT}" = 1 ] && ${INSTALL_PREFIX}/${ZAF_BIN_DIR}/zaf update [ "${ZAF_GIT}" = 1 ] && ${INSTALL_PREFIX}/${ZAF_BIN_DIR}/zaf update
${INSTALL_PREFIX}/${ZAF_BIN_DIR}/zaf reinstall zaf || zaf_err "Error installing zaf plugin." ${INSTALL_PREFIX}/${ZAF_BIN_DIR}/zaf reinstall zaf || zaf_err "Error installing zaf plugin."
${INSTALL_PREFIX}/${ZAF_BIN_DIR}/zaf agent-config || zaf_err "Error configuring agent." ${INSTALL_PREFIX}/${ZAF_BIN_DIR}/zaf agent-config || zaf_err "Error configuring agent."
if zaf_is_root && ! zaf_test_item zaf.framework_version; then zaf_os_specific zaf_postconfigure_os
if zaf_is_root && ! zaf_test_item zaf.framework_version; then
echo "Something is wrong with zabbix agent config." echo "Something is wrong with zabbix agent config."
echo "Ensure that zabbix_agentd reads ${ZAF_AGENT_CONFIG}" echo "Ensure that zabbix_agentd reads ${ZAF_AGENT_CONFIG}"
echo "and there is Include=${ZAF_AGENT_CONFIGD} directive inside." echo "and there is Include=${ZAF_AGENT_CONFIGD} directive inside."
echo "Does ${ZAF_AGENT_RESTART} work?" echo "Does ${ZAF_AGENT_RESTART} work?"
exit 1 exit 1
fi fi
else else
[ "${ZAF_GIT}" = 1 ] && [ -n "${INSTALL_PREFIX}" ] && git clone "${ZAF_REPO_GITURL}" "${INSTALL_PREFIX}/${ZAF_REPO_DIR}" [ "${ZAF_GIT}" = 1 ] && [ -n "${INSTALL_PREFIX}" ] && git clone "${ZAF_REPO_GITURL}" "${INSTALL_PREFIX}/${ZAF_REPO_DIR}"
fi fi
zaf_wrn "Install done. Use 'zaf' to get started." zaf_wrn "Install done. Use 'zaf' to get started."
true true
} }
@@ -296,16 +425,18 @@ zaf_postconfigure() {
if ! [ -f README.md ]; then if ! [ -f README.md ]; then
# Hardcoded variables # Hardcoded variables
ZAF_VERSION="1.2" ZAF_VERSION="1.4"
ZAF_GITBRANCH="1.2"
ZAF_URL="https://github.com/limosek/zaf"
ZAF_RAW_URL="https://raw.githubusercontent.com/limosek/zaf"
export ZAF_TMP_DIR="/tmp/zaf-installer" export ZAF_TMP_DIR="/tmp/zaf-installer"
export ZAF_DIR="$ZAF_TMP_DIR/zaf" export ZAF_DIR="$ZAF_TMP_DIR/zaf"
if [ -n "$ZAF_PROXY" ]; then
export ALL_PROXY="$ZAF_PROXY"
export http_proxy="$ZAF_PROXY"
export https_proxy="$ZAF_PROXY"
fi
mkdir -p $ZAF_TMP_DIR mkdir -p $ZAF_TMP_DIR
if ! which curl >/dev/null; if ! zaf_which curl >/dev/null && ! zaf_which wget >/dev/null;
then then
zaf_err "Curl not found. Cannot continue. Please install it." zaf_err "Curl or wget not found. Cannot continue. Please install it."
fi fi
echo "Installing from url $url..." echo "Installing from url $url..."
[ -z "$*" ] && auto=auto [ -z "$*" ] && auto=auto
@@ -315,7 +446,7 @@ if ! [ -f README.md ]; then
fi fi
# Try to load local downloaded libs # Try to load local downloaded libs
if ! type zaf_version >/dev/null; then if ! type zaf_version >/dev/null 2>/dev/null; then
. lib/zaf.lib.sh . lib/zaf.lib.sh
. lib/plugin.lib.sh . lib/plugin.lib.sh
. lib/os.lib.sh . lib/os.lib.sh
@@ -344,17 +475,20 @@ zaf_tmp_init
# Read options as config for ZAF # Read options as config for ZAF
for pair in "$@"; do for pair in "$@"; do
echo $pair | grep -q '^ZAF\_' || continue echo $pair | grep -q '^ZAF\_' || continue
option=$(echo $pair|cut -d '=' -f 1) option=$(echo $pair|cut -d '=' -f 1)
value=$(echo $pair|cut -d '=' -f 2-) value=$(echo $pair|cut -d '=' -f 2-)
eval "C_${option}='$value'" eval "C_${option}='$value'"
zaf_wrn "Overriding $option from cmdline." zaf_wrn "Overriding $option from cmdline."
done done
[ -z "$C_ZAF_TMP_DIR" ] && C_ZAF_TMP_DIR="/tmp/" [ -z "$C_ZAF_TMP_DIR" ] && C_ZAF_TMP_DIR="/tmp/"
if [ -n "$ZAF_PROXY" ]; then
export ALL_PROXY="$ZAF_PROXY"
fi
case $1 in case $1 in
interactive) interactive)
shift shift
INSTALL_MODE=interactive INSTALL_MODE=interactive
zaf_preconfigure zaf_preconfigure
zaf_configure "$@" zaf_configure "$@"
@@ -362,52 +496,52 @@ interactive)
zaf_postconfigure zaf_postconfigure
;; ;;
auto) auto)
shift shift
INSTALL_MODE=auto INSTALL_MODE=auto
zaf_preconfigure zaf_preconfigure
zaf_configure "$@" zaf_configure "$@"
zaf_install_all zaf_install_all
zaf_postconfigure zaf_postconfigure
;; ;;
debug-auto) debug-auto)
shift; shift;
ZAF_DEBUG=4 ZAF_DEBUG=4
INSTALL_MODE=auto INSTALL_MODE=auto
zaf_preconfigure zaf_preconfigure
zaf_configure "$@" zaf_configure "$@"
zaf_install_all zaf_install_all
zaf_postconfigure zaf_postconfigure
;; ;;
debug-interactive) debug-interactive)
shift; shift;
ZAF_DEBUG=4 ZAF_DEBUG=4
INSTALL_MODE=interactive INSTALL_MODE=interactive
zaf_preconfigure zaf_preconfigure
zaf_configure "$@" zaf_configure "$@"
zaf_install_all zaf_install_all
zaf_postconfigure zaf_postconfigure
;; ;;
debug) debug)
shift; shift;
ZAF_DEBUG=4 ZAF_DEBUG=4
INSTALL_MODE=auto INSTALL_MODE=auto
zaf_preconfigure zaf_preconfigure
zaf_configure "$@" zaf_configure "$@"
zaf_install_all zaf_install_all
zaf_postconfigure zaf_postconfigure
;; ;;
reconf) reconf)
shift; shift;
rm -f $ZAF_CFG_FILE rm -f $ZAF_CFG_FILE
INSTALL_MODE=auto INSTALL_MODE=auto
zaf_preconfigure reconf zaf_preconfigure reconf
zaf_configure "$@" zaf_configure "$@"
zaf_postconfigure zaf_postconfigure
;; ;;
install) install)
INSTALL_MODE=auto INSTALL_MODE=auto
zaf_preconfigure nor zaf_preconfigure nor
zaf_configure "$@" zaf_configure "$@"
zaf_install_all zaf_install_all
zaf_postconfigure zaf_postconfigure
;; ;;
@@ -415,16 +549,18 @@ install)
echo echo
echo "Please specify how to install." echo "Please specify how to install."
echo "install.sh {auto|interactive|debug-auto|debug-interactive|reconf} [Agent-Options] [Zaf-Options]" echo "install.sh {auto|interactive|debug-auto|debug-interactive|reconf} [Agent-Options] [Zaf-Options]"
echo "scratch means that config file will be created from scratch" echo "scratch means that config file will be created from scratch"
echo " Agent-Options: Z_Option=value [...]" echo " Agent-Options: Z_Option=value [...]"
echo " Zaf-Options: ZAF_OPT=value [...]" echo " Server-Options: S_Option=value [...]"
echo " Zaf-Options: ZAF_OPT=value [...]"
echo " To unset Agent-Option use Z_Option=''" echo " To unset Agent-Option use Z_Option=''"
echo echo
echo "Example 1 (default install): install.sh auto" echo "Example 1 (default install): install.sh auto"
echo 'Example 2 (preconfigure agent options): install.sh auto A_Server=zabbix.server A_ServerActive=zabbix.server A_Hostname=$(hostname)' echo 'Example 2 (preconfigure agent options): install.sh auto Z_Server=zabbix.server Z_ServerActive=zabbix.server Z_Hostname=$(hostname)'
echo "Example 3 (preconfigure zaf packaging system to use): install.sh auto ZAF_PKG=opkg" echo 'Example 3 (preconfigure server options): install.sh auto S_StartPollers=10 S_ListenPort=10051'
echo "Example 4 (interactive): install.sh interactive" echo "Example 4 (preconfigure zaf packaging system to use): install.sh auto ZAF_PKG=opkg"
echo echo "Example 5 (interactive): install.sh interactive"
echo
exit 1 exit 1
esac esac

10
ipk.mk Normal file
View File

@@ -0,0 +1,10 @@
# Makefile for generating openwrt ipk packages
# Contrinutions welcome :)
ifeq ($(IPK_PKG),)
IPK_PKG=$(shell . lib/zaf.lib.sh; echo out/zaf-$$ZAF_VERSION.ipk)
endif
$(IPK_PKG):
@echo "Not supported yet. Contributions welcomed! :) "; exit 2

View File

@@ -1,8 +1,8 @@
#!/bin/sh #!/bin/sh
throw() { throw() {
echo "$*" >&2 echo "$*" >&2
exit 1 exit 1
} }
BRIEF=0 BRIEF=0
@@ -12,197 +12,197 @@ NO_HEAD=0
NORMALIZE_SOLIDUS=0 NORMALIZE_SOLIDUS=0
usage() { usage() {
echo echo
echo "Usage: JSON.sh [-b] [-l] [-p] [-s] [-h]" echo "Usage: JSON.sh [-b] [-l] [-p] [-s] [-h]"
echo echo
echo "-p - Prune empty. Exclude fields with empty values." echo "-p - Prune empty. Exclude fields with empty values."
echo "-l - Leaf only. Only show leaf nodes, which stops data duplication." echo "-l - Leaf only. Only show leaf nodes, which stops data duplication."
echo "-b - Brief. Combines 'Leaf only' and 'Prune empty' options." echo "-b - Brief. Combines 'Leaf only' and 'Prune empty' options."
echo "-n - No-head. Do not show nodes that have no path (lines that start with [])." echo "-n - No-head. Do not show nodes that have no path (lines that start with [])."
echo "-s - Remove escaping of the solidus symbol (stright slash)." echo "-s - Remove escaping of the solidus symbol (stright slash)."
echo "-h - This help text." echo "-h - This help text."
echo echo
} }
parse_options() { parse_options() {
set -- "$@" set -- "$@"
local ARGN=$# local ARGN=$#
while [ "$ARGN" -ne 0 ] while [ "$ARGN" -ne 0 ]
do do
case $1 in case $1 in
-h) usage -h) usage
exit 0 exit 0
;; ;;
-b) BRIEF=1 -b) BRIEF=1
LEAFONLY=1 LEAFONLY=1
PRUNE=1 PRUNE=1
;; ;;
-l) LEAFONLY=1 -l) LEAFONLY=1
;; ;;
-p) PRUNE=1 -p) PRUNE=1
;; ;;
-n) NO_HEAD=1 -n) NO_HEAD=1
;; ;;
-s) NORMALIZE_SOLIDUS=1 -s) NORMALIZE_SOLIDUS=1
;; ;;
?*) echo "ERROR: Unknown option." ?*) echo "ERROR: Unknown option."
usage usage
exit 0 exit 0
;; ;;
esac esac
shift 1 shift 1
ARGN=$((ARGN-1)) ARGN=$((ARGN-1))
done done
} }
awk_egrep () { awk_egrep () {
local pattern_string=$1 local pattern_string=$1
gawk '{ gawk '{
while ($0) { while ($0) {
start=match($0, pattern); start=match($0, pattern);
token=substr($0, start, RLENGTH); token=substr($0, start, RLENGTH);
print token; print token;
$0=substr($0, start+RLENGTH); $0=substr($0, start+RLENGTH);
} }
}' pattern="$pattern_string" }' pattern="$pattern_string"
} }
tokenize () { tokenize () {
local GREP local GREP
local ESCAPE local ESCAPE
local CHAR local CHAR
if echo "test string" | egrep -ao --color=never "test" >/dev/null 2>&1 if echo "test string" | egrep -ao --color=never "test" >/dev/null 2>&1
then then
GREP='egrep -ao --color=never' GREP='egrep -ao --color=never'
else else
GREP='egrep -ao' GREP='egrep -ao'
fi fi
if echo "test string" | egrep -o "test" >/dev/null 2>&1 if echo "test string" | egrep -o "test" >/dev/null 2>&1
then then
ESCAPE='(\\[^u[:cntrl:]]|\\u[0-9a-fA-F]{4})' ESCAPE='(\\[^u[:cntrl:]]|\\u[0-9a-fA-F]{4})'
CHAR='[^[:cntrl:]"\\]' CHAR='[^[:cntrl:]"\\]'
else else
GREP=awk_egrep GREP=awk_egrep
ESCAPE='(\\\\[^u[:cntrl:]]|\\u[0-9a-fA-F]{4})' ESCAPE='(\\\\[^u[:cntrl:]]|\\u[0-9a-fA-F]{4})'
CHAR='[^[:cntrl:]"\\\\]' CHAR='[^[:cntrl:]"\\\\]'
fi fi
local STRING="\"$CHAR*($ESCAPE$CHAR*)*\"" local STRING="\"$CHAR*($ESCAPE$CHAR*)*\""
local NUMBER='-?(0|[1-9][0-9]*)([.][0-9]*)?([eE][+-]?[0-9]*)?' local NUMBER='-?(0|[1-9][0-9]*)([.][0-9]*)?([eE][+-]?[0-9]*)?'
local KEYWORD='null|false|true' local KEYWORD='null|false|true'
local SPACE='[[:space:]]+' local SPACE='[[:space:]]+'
# Force zsh to expand $A into multiple words # Force zsh to expand $A into multiple words
local is_wordsplit_disabled=$(unsetopt 2>/dev/null | grep -c '^shwordsplit$') local is_wordsplit_disabled=$(unsetopt 2>/dev/null | grep -c '^shwordsplit$')
if [ $is_wordsplit_disabled != 0 ]; then setopt shwordsplit; fi if [ $is_wordsplit_disabled != 0 ]; then setopt shwordsplit; fi
$GREP "$STRING|$NUMBER|$KEYWORD|$SPACE|." | egrep -v "^$SPACE$" $GREP "$STRING|$NUMBER|$KEYWORD|$SPACE|." | egrep -v "^$SPACE$"
if [ $is_wordsplit_disabled != 0 ]; then unsetopt shwordsplit; fi if [ $is_wordsplit_disabled != 0 ]; then unsetopt shwordsplit; fi
} }
parse_array () { parse_array () {
local index=0 local index=0
local ary='' local ary=''
read -r token read -r token
case "$token" in case "$token" in
']') ;; ']') ;;
*) *)
while : while :
do do
parse_value "$1" "$index" parse_value "$1" "$index"
index=$((index+1)) index=$((index+1))
ary="$ary""$value" ary="$ary""$value"
read -r token read -r token
case "$token" in case "$token" in
']') break ;; ']') break ;;
',') ary="$ary," ;; ',') ary="$ary," ;;
*) throw "EXPECTED , or ] GOT ${token:-EOF}" ;; *) throw "EXPECTED , or ] GOT ${token:-EOF}" ;;
esac esac
read -r token read -r token
done done
;; ;;
esac esac
[ "$BRIEF" -eq 0 ] && value=$(printf '[%s]' "$ary") || value= [ "$BRIEF" -eq 0 ] && value=$(printf '[%s]' "$ary") || value=
: :
} }
parse_object () { parse_object () {
local key local key
local obj='' local obj=''
read -r token read -r token
case "$token" in case "$token" in
'}') ;; '}') ;;
*) *)
while : while :
do do
case "$token" in case "$token" in
'"'*'"') key=$token ;; '"'*'"') key=$token ;;
*) throw "EXPECTED string GOT ${token:-EOF}" ;; *) throw "EXPECTED string GOT ${token:-EOF}" ;;
esac esac
read -r token read -r token
case "$token" in case "$token" in
':') ;; ':') ;;
*) throw "EXPECTED : GOT ${token:-EOF}" ;; *) throw "EXPECTED : GOT ${token:-EOF}" ;;
esac esac
read -r token read -r token
parse_value "$1" "$key" parse_value "$1" "$key"
obj="$obj$key:$value" obj="$obj$key:$value"
read -r token read -r token
case "$token" in case "$token" in
'}') break ;; '}') break ;;
',') obj="$obj," ;; ',') obj="$obj," ;;
*) throw "EXPECTED , or } GOT ${token:-EOF}" ;; *) throw "EXPECTED , or } GOT ${token:-EOF}" ;;
esac esac
read -r token read -r token
done done
;; ;;
esac esac
[ "$BRIEF" -eq 0 ] && value=$(printf '{%s}' "$obj") || value= [ "$BRIEF" -eq 0 ] && value=$(printf '{%s}' "$obj") || value=
: :
} }
parse_value () { parse_value () {
local jpath="${1:+$1,}$2" isleaf=0 isempty=0 print=0 local jpath="${1:+$1,}$2" isleaf=0 isempty=0 print=0
case "$token" in case "$token" in
'{') parse_object "$jpath" ;; '{') parse_object "$jpath" ;;
'[') parse_array "$jpath" ;; '[') parse_array "$jpath" ;;
# At this point, the only valid single-character tokens are digits. # At this point, the only valid single-character tokens are digits.
''|[!0-9]) throw "EXPECTED value GOT ${token:-EOF}" ;; ''|[!0-9]) throw "EXPECTED value GOT ${token:-EOF}" ;;
*) value=$token *) value=$token
# if asked, replace solidus ("\/") in json strings with normalized value: "/" # if asked, replace solidus ("\/") in json strings with normalized value: "/"
[ "$NORMALIZE_SOLIDUS" -eq 1 ] && value=$(echo "$value" | sed 's#\\/#/#g') [ "$NORMALIZE_SOLIDUS" -eq 1 ] && value=$(echo "$value" | sed 's#\\/#/#g')
isleaf=1 isleaf=1
[ "$value" = '""' ] && isempty=1 [ "$value" = '""' ] && isempty=1
;; ;;
esac esac
[ "$value" = '' ] && return [ "$value" = '' ] && return
[ "$NO_HEAD" -eq 1 ] && [ -z "$jpath" ] && return [ "$NO_HEAD" -eq 1 ] && [ -z "$jpath" ] && return
[ "$LEAFONLY" -eq 0 ] && [ "$PRUNE" -eq 0 ] && print=1 [ "$LEAFONLY" -eq 0 ] && [ "$PRUNE" -eq 0 ] && print=1
[ "$LEAFONLY" -eq 1 ] && [ "$isleaf" -eq 1 ] && [ $PRUNE -eq 0 ] && print=1 [ "$LEAFONLY" -eq 1 ] && [ "$isleaf" -eq 1 ] && [ $PRUNE -eq 0 ] && print=1
[ "$LEAFONLY" -eq 0 ] && [ "$PRUNE" -eq 1 ] && [ "$isempty" -eq 0 ] && print=1 [ "$LEAFONLY" -eq 0 ] && [ "$PRUNE" -eq 1 ] && [ "$isempty" -eq 0 ] && print=1
[ "$LEAFONLY" -eq 1 ] && [ "$isleaf" -eq 1 ] && \ [ "$LEAFONLY" -eq 1 ] && [ "$isleaf" -eq 1 ] && \
[ $PRUNE -eq 1 ] && [ $isempty -eq 0 ] && print=1 [ $PRUNE -eq 1 ] && [ $isempty -eq 0 ] && print=1
[ "$print" -eq 1 ] && printf "[%s]\t%s\n" "$jpath" "$value" [ "$print" -eq 1 ] && printf "[%s]\t%s\n" "$jpath" "$value"
: :
} }
parse () { parse () {
read -r token read -r token
parse_value parse_value
read -r token read -r token
case "$token" in case "$token" in
'') ;; '') ;;
*) throw "EXPECTED EOF GOT $token" ;; *) throw "EXPECTED EOF GOT $token" ;;
esac esac
} }
if ([ "$0" = "$BASH_SOURCE" ] || ! [ -n "$BASH_SOURCE" ]); if ([ "$0" = "$BASH_SOURCE" ] || ! [ -n "$BASH_SOURCE" ]);
then then
parse_options "$@" parse_options "$@"
tokenize | parse tokenize | parse
fi fi
# vi: expandtab sw=2 ts=2 # vi: expandtab sw=2 ts=2

View File

@@ -1,27 +1,25 @@
# Zaf cache related functions # Zaf cache related functions
zaf_cache_init(){ zaf_cache_init(){
[ -z "$ZAF_CACHE_DIR" ] && ZAF_CACHE_DIR=${ZAF_TMP_DIR}/zafc local files
if [ -w $ZAF_CACHE_DIR ]; then local file
zaf_trc "Cache: Removing stale entries"
(cd $ZAF_CACHE_DIR && find ./ -type f -name '*.info' -mmin +1 2>/dev/null | \ if [ "$ZAF_CACHE_DIR" = "/tmp/zafc" ] && ! [ -d "$ZAF_CACHE_DIR" ]; then
while read line ; do mkdir -p $ZAF_CACHE_DIR
rm -f $line $(basename $line .info) chown $ZAF_FILES_UID $ZAF_CACHE_DIR >/dev/null 2>/dev/null
done fi
) if ! [ -w $ZAF_CACHE_DIR ]; then
else
zaf_dbg "Cache dir $ZAF_CACHE_DIR is not accessible! Disabling cache." zaf_dbg "Cache dir $ZAF_CACHE_DIR is not accessible! Disabling cache."
fi fi
} }
zaf_cache_clean(){ zaf_cache_clean(){
if [ -n "$ZAF_CACHE_DIR" ]; then local files
if [ -w "$ZAF_CACHE_DIR" ]; then
zaf_wrn "Removing cache entries" zaf_wrn "Removing cache entries"
(cd $ZAF_CACHE_DIR && find ./ -type f -name '*.info' 2>/dev/null | \ files=$(find $ZAF_CACHE_DIR/ -type f)
while read line ; do [ -n "$files" ] && rm -f $files
rm -f $line $(basename $line .info)
done
)
else else
zaf_dbg "Cache dir not set. Disabling cache." zaf_dbg "Cache dir not set. Disabling cache."
fi fi
@@ -33,45 +31,78 @@ zaf_cache_key(){
echo "$1" | (md5sum - ||md5) 2>/dev/null | cut -d ' ' -f 1 echo "$1" | (md5sum - ||md5) 2>/dev/null | cut -d ' ' -f 1
} }
# Wait for lock
# $1 - key
zaf_cache_lock(){
local lockfile
lockfile="${ZAF_CACHE_DIR}/${key}.lock"
[ -f "$lockfile" ] && sleep 1
[ -f "$lockfile" ] && return 1
return 0
}
# Unlock cache key
# $1 - key
zaf_cache_unlock(){
local lockfile
lockfile="${ZAF_CACHE_DIR}/${key}.lock"
rm -f $lockfile
}
# Put object into cache # Put object into cache
# $1 key # $1 key
# $2 value # $2 value
# $3 lifetime in seconds # $3 lifetime in seconds
zaf_tocache(){ zaf_tocache(){
! [ -w $ZAF_CACHE_DIR ] && return 1 ! [ -w $ZAF_CACHE_DIR ] && return
local key local key
local value local value
local expiry local expiry
local infofile
local datafile
key=$(zaf_cache_key "$1") key=$(zaf_cache_key "$1")
rm -f $ZAF_CACHE_DIR/$key $ZAF_CACHE_DIR/${key}.info datafile=${ZAF_CACHE_DIR}/$key
echo "$2" >$ZAF_CACHE_DIR/$key infofile=${ZAF_CACHE_DIR}/${key}.info
echo "$1" >$ZAF_CACHE_DIR/${key}.info
zaf_cache_lock "$key" || { zaf_wrn "Cache: Entry $1[$key] locked!"; return 1; }
rm -f $datafile $infofile
echo "$2" >$datafile
echo "$1" >$infofile
expiry=$(zaf_date_add "$3") expiry=$(zaf_date_add "$3")
zaf_trc "Cache: Saving entry $1[$key,expiry=$expiry]" zaf_trc "Cache: Saving entry $1[$key,expiry=$expiry]"
touch -m -d "$expiry" $ZAF_CACHE_DIR/${key}.info touch -m -d "$expiry" $infofile
zaf_cache_unlock $key
} }
# Put object into cache from stdin and copy to stdout # Put object into cache from stdin and copy to stdout
# $1 key # $1 key
# $2 lifetime in seconds # $2 lifetime in seconds
zaf_tocache_stdin(){ zaf_tocache_stdin(){
! [ -w $ZAF_CACHE_DIR ] && return 1 ! [ -w $ZAF_CACHE_DIR ] && { cat; return; }
local key local key
local expiry local expiry
local infofile
local datafile
key=$(zaf_cache_key "$1") key=$(zaf_cache_key "$1")
rm -f $ZAF_CACHE_DIR/$key $ZAF_CACHE_DIR/${key}.info datafile=${ZAF_CACHE_DIR}/$key
cat >$ZAF_CACHE_DIR/$key lockfile=${ZAF_CACHE_DIR}/${key}.lock
if [ -s $ZAF_CACHE_DIR/$key ]; then infofile=${ZAF_CACHE_DIR}/${key}.info
expiry="$(zaf_date_add $2)"
echo "$1 [key=$key,expiry=$expiry]" >$ZAF_CACHE_DIR/${key}.info zaf_cache_lock "$key" || { zaf_wrn "Cache: Entry $1[$key] locked!"; return 1; }
zaf_trc "Cache: Saving entry $1[key=$key,expiry=$expiry]"
touch -m -d "$expiry" $ZAF_CACHE_DIR/$key.info rm -f $datafile $infofile
cat $ZAF_CACHE_DIR/$key cat >$datafile
else expiry="$(zaf_date_add $2)"
rm -f "$ZAF_CACHE_DIR/$key" echo "$1 [key=$key,expiry=$expiry]" >$infofile
fi zaf_trc "Cache: Saving entry $1[key=$key,expiry=$expiry]"
touch -m -d "$expiry" $infofile
zaf_cache_unlock "$key"
cat $datafile
} }
# Remove entry from cache # Remove entry from cache
@@ -81,15 +112,16 @@ zaf_cache_delentry(){
local key local key
key=$(zaf_cache_key "$1") key=$(zaf_cache_key "$1")
zaf_trc "Cache: removing $1($key) from cache" zaf_trc "Cache: removing $1($key) from cache"
rm -f "$ZAF_CACHE_DIR/$key*" rm -f "${ZAF_CACHE_DIR}/$key*"
} }
# List entries in cache # List entries in cache
zaf_cache_list(){ zaf_cache_list(){
! [ -w $ZAF_CACHE_DIR ] && return 1
local i local i
ls $ZAF_CACHE_DIR/*info >/dev/null 2>/dev/null || return 1 ls ${ZAF_CACHE_DIR}/*info >/dev/null 2>/dev/null || return 1
local key local key
for i in $ZAF_CACHE_DIR/*info; do for i in ${ZAF_CACHE_DIR}/*info; do
cat $i cat $i
done done
} }
@@ -97,18 +129,22 @@ zaf_cache_list(){
# Get object from cache # Get object from cache
# $1 key # $1 key
zaf_fromcache(){ zaf_fromcache(){
! [ -r $ZAF_CACHE_DIR ] || [ -n "$ZAF_NOCACHE" ] && return 1 ! [ -w $ZAF_CACHE_DIR ] && return 3
local key local key
local value local value
local infofile
local datafile
key=$(zaf_cache_key "$1") key=$(zaf_cache_key "$1")
if [ -f $ZAF_CACHE_DIR/$key ]; then datafile="${ZAF_CACHE_DIR}/${key}"
! [ -f "$ZAF_CACHE_DIR/$key.info" ] && { return 3; } infofile="${ZAF_CACHE_DIR}/${key}.info"
if [ "$ZAF_CACHE_DIR/$key.info" -nt "$ZAF_CACHE_DIR/$key" ]; then
if [ -f $datafile ]; then
if [ "$infofile" -nt "$datafile" ]; then
zaf_trc "Cache: serving $1($key) from cache" zaf_trc "Cache: serving $1($key) from cache"
cat $ZAF_CACHE_DIR/$key cat "$datafile"
else else
zaf_trc "Cache: removing old entry $1" zaf_cache_delentry $key
rm -f "$ZAF_CACHE_DIR/$key*"
return 2 return 2
fi fi
else else
@@ -117,3 +153,4 @@ zaf_fromcache(){
fi fi
} }

View File

@@ -5,6 +5,25 @@ zaf_ctrl_get_items() {
grep '^Item ' | cut -d ' ' -f 2 | cut -d ':' -f 1 | tr '\r\n' ' ' grep '^Item ' | cut -d ' ' -f 2 | cut -d ':' -f 1 | tr '\r\n' ' '
} }
# Get external item list from control on stdin
zaf_ctrl_get_extitems() {
grep '^ExtItem ' | cut -d ' ' -f 2 | cut -d ':' -f 1 | tr '\r\n' ' '
}
# Get external item body from stdin
# $1 itemname
zaf_ctrl_get_extitem_block() {
grep -v '^#' | awk '/^ExtItem '$1'/ { i=0;
while (i==0) {
getline;
if (/^\/ExtItem/) exit;
print $0;
}};
END {
exit i==0;
}'
}
# Get item body from stdin # Get item body from stdin
# $1 itemname # $1 itemname
zaf_ctrl_get_item_block() { zaf_ctrl_get_item_block() {
@@ -25,7 +44,7 @@ zaf_ctrl_get_global_block() {
grep -vE '^#[a-zA-Z ]' | awk '{ i=0; print $0; grep -vE '^#[a-zA-Z ]' | awk '{ i=0; print $0;
while (i==0) { while (i==0) {
getline; getline;
if (/^Item /) exit; if (/^(Item |ExtItem)/) exit;
print $0; print $0;
}}' }}'
} }
@@ -33,7 +52,7 @@ zaf_ctrl_get_global_block() {
# Get item multiline option # Get item multiline option
# $1 optionname # $1 optionname
zaf_block_get_moption() { zaf_block_get_moption() {
awk '/^'$1'::$/ { i=0; awk '/^'$1'::$/ { i=0; if (!/::/) print $0;
while (i==0) { while (i==0) {
getline; getline;
if (/^::$/) {i=1; continue;}; if (/^::$/) {i=1; continue;};
@@ -57,7 +76,7 @@ zaf_block_get_option() {
zaf_ctrl_get_global_option() { zaf_ctrl_get_global_option() {
local ctrlvar local ctrlvar
local ctrlopt local ctrlopt
ctrlopt="ZAF_CTRL_$(zaf_stripctrl $2)" ctrlopt="ZAF_CTRL_$(zaf_stripctrl $2)"
eval ctrlvar=\$$ctrlopt eval ctrlvar=\$$ctrlopt
if [ -n "$ctrlvar" ]; then if [ -n "$ctrlvar" ]; then
@@ -68,6 +87,7 @@ zaf_ctrl_get_global_option() {
|| zaf_ctrl_get_global_block <$1 | zaf_block_get_option "$2" || zaf_ctrl_get_global_block <$1 | zaf_block_get_option "$2"
fi fi
} }
# Get item specific option (single or multiline) # Get item specific option (single or multiline)
# $1 - control file # $1 - control file
# $2 - item name # $2 - item name
@@ -87,16 +107,38 @@ zaf_ctrl_get_item_option() {
fi fi
} }
# Get external item specific option (single or multiline)
# $1 - control file
# $2 - item name
# $3 - option name
zaf_ctrl_get_extitem_option() {
local ctrlvar
local ctrlopt
ctrlopt="ZAF_CTRLI_$(zaf_stripctrl $2)_$(zaf_stripctrl $3)"
eval ctrlvar=\$$ctrlopt
if [ -n "$ctrlvar" ]; then
zaf_dbg "Overriding item control field $2/$3 from env $ctrlopt($ctrlvar)"
echo $ctrlopt
else
zaf_ctrl_get_extitem_block <$1 "$2" | zaf_block_get_moption "$3" \
|| zaf_ctrl_get_extitem_block <$1 "$2" | zaf_block_get_option "$3"
fi
}
# Check dependencies based on control file # Check dependencies based on control file
zaf_ctrl_check_deps() { zaf_ctrl_check_deps() {
local deps local deps
deps=$(zaf_ctrl_get_global_block <$1 | zaf_block_get_option "Depends-${ZAF_PKG}" ) if [ -n "$ZAF_PKG" ]; then
if ! zaf_os_specific zaf_check_deps $deps; then deps=$(zaf_ctrl_get_global_block <$1 | zaf_block_get_option "Depends-${ZAF_PKG}" )
zaf_err "Missing one of dependend system packages: $deps"
if ! zaf_os_specific zaf_check_deps $deps; then
zaf_err "Missing one of dependend system packages: $deps"
fi
fi fi
deps=$(zaf_ctrl_get_global_block <$1 | zaf_block_get_option "Depends-bin" ) deps=$(zaf_ctrl_get_global_block <$1 | zaf_block_get_option "Depends-bin" )
for cmd in $deps; do for cmd in $deps; do
if ! which $cmd >/dev/null; then if ! zaf_which $cmd >/dev/null; then
zaf_err "Missing binary dependency $cmd. Please install it first." zaf_err "Missing binary dependency $cmd. Please install it first."
fi fi
done done
@@ -115,17 +157,19 @@ zaf_ctrl_sudo() {
pdir="$3" pdir="$3"
plugin=$1 plugin=$1
sudo=$(zaf_ctrl_get_global_option $2 "Sudo" | zaf_far '{PLUGINDIR}' "${plugindir}")
[ -z "$sudo" ] || [ -z "$ZAF_SUDOERSD" ] && return
! [ -d "$ZAF_SUDOERSD" ] && { zaf_wrn "$ZAF_SUDOERSD nonexistent! Skipping sudo install!"; return 1; } ! [ -d "$ZAF_SUDOERSD" ] && { zaf_wrn "$ZAF_SUDOERSD nonexistent! Skipping sudo install!"; return 1; }
zaf_dbg "Installing sudoers entry $ZAF_SUDOERSD/zaf_$plugin" zaf_dbg "Installing sudoers entry $ZAF_SUDOERSD/zaf_$plugin"
sudo=$(zaf_ctrl_get_global_option $2 "Sudo" | zaf_far '{PLUGINDIR}' "${plugindir}")
[ -z "$sudo" ] && return # Nothing to install [ -z "$sudo" ] && return # Nothing to install
if ! which sudo >/dev/null; then if ! zaf_which sudo >/dev/null; then
zaf_wrn "Sudo needed bud not installed?" zaf_wrn "Sudo needed bud not installed?"
fi fi
cmd=$(echo $sudo | cut -d ' ' -f 1) cmd=$(echo $sudo | cut -d ' ' -f 1)
parms=$(echo $sudo | cut -d ' ' -f 2-) parms=$(echo $sudo | cut -d ' ' -f 2-)
if which $cmd >/dev/null ; then if zaf_which $cmd >/dev/null ; then
(echo "zabbix ALL=NOPASSWD:SETENV: $(which $cmd) $(echo $parms | tr '%' '*')";echo) >$ZAF_SUDOERSD/zaf_$plugin || zaf_err "Error during zaf_ctrl_sudo" (echo "zabbix ALL=NOPASSWD:SETENV: $(zaf_which $cmd) $(echo $parms | tr '%' '*')";echo) >$ZAF_SUDOERSD/zaf_$plugin || zaf_err "Error during zaf_ctrl_sudo"
chmod 0440 $ZAF_SUDOERSD/zaf_$plugin chmod 0440 $ZAF_SUDOERSD/zaf_$plugin
else else
zaf_err "Cannot find binary '$cmd' to put into sudoers." zaf_err "Cannot find binary '$cmd' to put into sudoers."
@@ -143,14 +187,15 @@ zaf_ctrl_cron() {
pdir="$3" pdir="$3"
plugin=$1 plugin=$1
cron=$(zaf_ctrl_get_global_option $2 "Cron")
[ -z "$cron" ] || [ -z "$ZAF_CROND" ] && return
! [ -d "$ZAF_CROND" ] && { zaf_wrn "$ZAF_CROND nonexistent! Skipping cron install!"; return 1; } ! [ -d "$ZAF_CROND" ] && { zaf_wrn "$ZAF_CROND nonexistent! Skipping cron install!"; return 1; }
zaf_dbg "Installing cron entry $ZAF_CROND/zaf_$plugin" zaf_dbg "Installing cron entry $ZAF_CROND/zaf_$plugin"
cron=$(zaf_ctrl_get_global_option $2 "Cron")
[ -z "$cron" ] && return # Nothing to install [ -z "$cron" ] && return # Nothing to install
zaf_ctrl_get_global_option $2 "Cron" | zaf_far '{PLUGINDIR}' "${plugindir}" >$ZAF_CROND/zaf_$plugin || zaf_err "Error during zaf_ctrl_cron" zaf_ctrl_get_global_option $2 "Cron" | zaf_far '{PLUGINDIR}' "${plugindir}" >$ZAF_CROND/zaf_$plugin || zaf_err "Error during zaf_ctrl_cron"
} }
# Install files defined to be installed in control to plugun directory # Install files defined to be installed in control to plugin directory
# $1 pluginurl # $1 pluginurl
# $2 control # $2 control
# $3 plugindir # $3 plugindir
@@ -164,27 +209,26 @@ zaf_ctrl_install() {
pdir="$3" pdir="$3"
(set -e (set -e
binaries=$(zaf_ctrl_get_global_option $2 "Install-bin") binaries=$(zaf_ctrl_get_global_option $2 "Install-bin")" "$(zaf_ctrl_get_global_option $2 "Install-cmd")
for b in $binaries; do for b in $binaries; do
zaf_fetch_url "$1/$b" >"${ZAF_TMP_DIR}/$b" zaf_fetch_url "$1/$b" >"${ZAF_TMP_DIR}/$b"
zaf_install_bin "${ZAF_TMP_DIR}/$b" "$pdir" zaf_install_bin "${ZAF_TMP_DIR}/$b" "$pdir"
done done
files=$(zaf_ctrl_get_global_option $2 "Install-files") files=$(zaf_ctrl_get_global_option $2 "Install-files")
for f in $files; do for f in $files; do
zaf_fetch_url "$1/$b" >"${ZAF_TMP_DIR}/$b" zaf_fetch_url "$1/$f" >"${ZAF_TMP_DIR}/$f"
zaf_install "${ZAF_TMP_DIR}/$b" "$pdir" zaf_install "${ZAF_TMP_DIR}/$f" "$pdir"
done done
script=$(zaf_ctrl_get_global_option $2 "Install-script")
[ -n "$script" ] && eval "$script"
true true
) || zaf_err "Error during zaf_ctrl_install" ) || zaf_err "Error during zaf_ctrl_install"
} }
# Generates zabbix cfg from control file # Generates zabbix items cfg from control file
# $1 control # $1 control
# $2 pluginname # $2 pluginname
# $3 if nonempty, only return cfg, do not generate scripts # $3 if set, no script will be created
zaf_ctrl_generate_cfg() { # $4 if set, cmd is set always to $4
zaf_ctrl_generate_items_cfg() {
local items local items
local cmd local cmd
local iscript local iscript
@@ -199,54 +243,147 @@ zaf_ctrl_generate_cfg() {
local zafparms local zafparms
items=$(zaf_ctrl_get_items <"$1") items=$(zaf_ctrl_get_items <"$1")
tmpfile=$ZAF_TMP_DIR/gencfg$$ tmpfile=$(zaf_tmpfile genparms)
(set -e (set -e
for i in $items; do for i in $items; do
iscript=$(zaf_stripctrl $i) iscript=$(zaf_stripctrl $i)
zaf_ctrl_get_item_option $1 $i "Parameters" >$tmpfile zaf_ctrl_get_item_option $1 $i "Parameters" >$tmpfile
if [ -s "$tmpfile" ]; then echo >>$tmpfile
ikey="$2.$i[*]" zafparams="";
args="" if [ -s "$tmpfile" ]; then
apos=1; ikey="$2.$i[*]"
while read pname pdefault pregex prest; do args=""
zafparams="$zafparams value=\"\$$apos\"; zaf_agentparm $pname $pdefault $pregex; export $pname; " apos=1;
args="$args \$$apos" while read pname pdefault pregex prest; do
apos=$(expr $apos + 1) [ -z "$pname" ] && continue
done <$tmpfile zaf_trc "Adding param $pname ($pdefault $pregex) to $i"
else zafparams="$zafparams value=\"\$$apos\"; zaf_agentparm $pname $pdefault $pregex; export $pname; "
ikey="$2.$i" args="$args \$$apos"
zafparams="" apos=$(expr $apos + 1)
args="" done <$tmpfile
fi else
env="export ITEM_KEY='$ikey'; export PLUGIN='$2'; export PATH=${ZAF_PLUGINS_DIR}/$2:$ZAF_LIB_DIR:\$PATH; cd ${ZAF_PLUGINS_DIR}/$2; . $ZAF_LIB_DIR/preload.sh; " ikey="$2.$i"
lock=$(zaf_ctrl_get_item_option $1 $i "Lock") zafparams=""
if [ -n "$lock" ]; then args=""
lock="${ZAF_LIB_DIR}/zaflock $lock " fi
fi env="export ITEM_KEY='$ikey'; export PLUGIN='$2'; export PATH=${ZAF_PLUGINS_DIR}/$2:$ZAF_LIB_DIR:\$PATH; cd ${ZAF_PLUGINS_DIR}/$2; . $ZAF_LIB_DIR/preload.sh; "
cache=$(zaf_ctrl_get_item_option $1 $i "Cache") lock=$(zaf_ctrl_get_item_option $1 $i "Lock")
if [ -n "$cache" ]; then if [ -n "$lock" ]; then
cache="${ZAF_LIB_DIR}/zafcache '$cache' " lock="${ZAF_LIB_DIR}/zaflock $lock "
fi fi
cmd=$(zaf_ctrl_get_item_option $1 $i "Cmd") cache=$(zaf_ctrl_get_item_option $1 $i "Cache")
if [ -n "$cmd" ]; then if [ -n "$cache" ]; then
printf "%s" "UserParameter=$ikey,${env}${zafparams}${preload}${cache}${lock}${cmd}"; echo cache="${ZAF_LIB_DIR}/zafcache '$cache' "
continue fi
fi ret=$(zaf_ctrl_get_item_option $1 $i "Return")
cmd=$(zaf_ctrl_get_item_option $1 $i "Script") retnull=$(zaf_ctrl_get_item_option $1 $i "Return-null")
if [ -n "$cmd" ]; then reterr=$(zaf_ctrl_get_item_option $1 $i "Return-error")
( echo "#!/bin/sh" if [ -n "$ret" ] || [ -n "$reterr" ] || [ -n "$retnull" ]; then
echo ". $ZAF_LIB_DIR/preload.sh; " retscr=" 1>\${tmpf}o 2>\${tmpf}e; ${ZAF_LIB_DIR}/zafret \${tmpf}o \${tmpf}e \$? '$ret' '$retnull' '$retempty' ";
zaf_ctrl_get_item_option $1 $i "Script" else
) >${ZAF_TMP_DIR}/${iscript}.sh; retscr="";
[ -z "$3" ] && zaf_install_bin ${ZAF_TMP_DIR}/${iscript}.sh ${ZAF_PLUGINS_DIR}/$2/ fi
printf "%s" "UserParameter=$ikey,${env}${preload}${zafparams}${cache}${lock}${ZAF_PLUGINS_DIR}/$2/${iscript}.sh ${args}"; echo if [ -z "$4" ]; then
rm -f ${ZAF_TMP_DIR}/${iscript}.sh cmd=$(zaf_ctrl_get_item_option $1 $i "Cmd")
continue; else
fi cmd="$4"
zaf_err "Item $i declared in control file but has no Cmd, Function or Script!" fi
if [ -n "$cmd" ]; then
printf "%s" "UserParameter=$ikey,${env}${zafparams}${preload}${cache}${lock}${cmd}${retscr}"; echo
continue
fi
cmd=$(zaf_ctrl_get_item_option $1 $i "Script")
if [ -n "$cmd" ]; then
( echo "#!/bin/sh"
echo ". $ZAF_LIB_DIR/preload.sh; "
zaf_ctrl_get_item_option $1 $i "Script"
) >${ZAF_TMP_DIR}/${iscript}.sh;
[ -z "$3" ] && zaf_install_bin ${ZAF_TMP_DIR}/${iscript}.sh ${ZAF_PLUGINS_DIR}/$2/
if [ -z "$4" ]; then
script="${ZAF_PLUGINS_DIR}/$2/${iscript}.sh"
else
script="$4"
fi
printf "%s" "UserParameter=$ikey,${env}${preload}${zafparams}${cache}${lock}$script ${args}"; echo
rm -f ${ZAF_TMP_DIR}/${iscript}.sh
continue;
fi
zaf_err "Item $i declared in control file but has no Cmd, Function or Script!"
done done
) || zaf_err "Error during zaf_ctrl_generate_cfg" ) || zaf_err "Error during zaf_ctrl_generate_items_cfg"
[ "$ZAF_DEBUG" -lt 4 ] && rm -f $tmpfile
}
# Generates zabbix items cfg from control file
# $1 control
# $2 pluginname
zaf_ctrl_generate_extitems_cfg() {
local items
local cmd
local iscript
local ikey
local lock
local cache
local tmpfile
local pname
local pdefault
local pregex
local prest
local zafparms
items=$(zaf_ctrl_get_extitems <"$1")
tmpfile=$(zaf_tmpfile genparms)
(set -e
for i in $items; do
iscript=$(zaf_stripctrl $i)
(zaf_ctrl_get_extitem_option $1 $i "Parameters"; echo) >$tmpfile
ikey="$2.$i"
if [ -s "$tmpfile" ]; then
args=""
apos=1;
while read pname pdefault pregex prest; do
zafparams="$zafparams value=\"\$$apos\"; zaf_agentparm $pname $pdefault $pregex; export $pname; "
args="$args \$$apos"
apos=$(expr $apos + 1)
done <$tmpfile
else
zafparams=""
args=""
fi
env="export ITEM_KEY='$ikey'; export PLUGIN='$2'; export PATH=${ZAF_PLUGINS_DIR}/$2:$ZAF_LIB_DIR:\$PATH; cd ${ZAF_PLUGINS_DIR}/$2; . $ZAF_LIB_DIR/preload.sh; "
lock=$(zaf_ctrl_get_extitem_option $1 $i "Lock")
if [ -n "$lock" ]; then
lock="${ZAF_LIB_DIR}/zaflock $lock "
fi
cache=$(zaf_ctrl_get_extitem_option $1 $i "Cache")
if [ -n "$cache" ]; then
cache="${ZAF_LIB_DIR}/zafcache '$cache' "
fi
ret=$(zaf_ctrl_get_extitem_option $1 $i "Return")
retnull=$(zaf_ctrl_get_extitem_option $1 $i "Return-null")
reterr=$(zaf_ctrl_get_extitem_option $1 $i "Return-error")
if [ -n "$ret" ] || [ -n "$reterr" ] || [ -n "$retnull" ]; then
retscr=" 1>\${tmpf}o 2>\${tmpf}e; ${ZAF_LIB_DIR}/zafret \${tmpf}o \${tmpf}e \$? '$ret' '$retnull' '$retempty' \$*";
else
retscr="";
fi
cmd=$(zaf_ctrl_get_extitem_option "$1" "$i" "Cmd")
if [ -n "$cmd" ]; then
echo "#!/bin/sh" >"${ZAF_SERVER_EXTSCRIPTS}/$ikey"
chmod +x "${ZAF_SERVER_EXTSCRIPTS}/$ikey"
(printf "%s" "${env}${zafparams}${preload}${cache}${lock}${cmd}${retscr}"; echo) >>"${ZAF_SERVER_EXTSCRIPTS}/$ikey"
continue
fi
cmd=$(zaf_ctrl_get_extitem_option "$1" "$i" "Script")
if [ -n "$cmd" ]; then
echo "#!/bin/sh" >"${ZAF_SERVER_EXTSCRIPTS}/$ikey"
chmod +x "${ZAF_SERVER_EXTSCRIPTS}/$ikey"
(printf "%s" "${env}${zafparams}${preload}${cache}${lock}${cmd}"; echo) >>"${ZAF_SERVER_EXTSCRIPTS}/$ikey"
continue;
fi
zaf_err "External item $i declared in control file but has no Cmd, Function or Script!"
done
) || zaf_err "Error during zaf_ctrl_generate_extitems_cfg"
rm -f $tmpfile rm -f $tmpfile
} }

View File

@@ -1,50 +1,71 @@
# Os related functions # Os related functions
zaf_configure_os_openwrt() { zaf_preconfigure_os_openwrt() {
ZAF_AGENT_RESTART="zaf agent-config ; /etc/init.d/zabbix_agentd restart" ZAF_AGENT_RESTART="/etc/init.d/zabbix_agentd restart"
ZAF_AGENT_CONFIGD="/var/run/zabbix_agentd.conf.d/" ZAF_AGENT_CONFIGD="/var/run/zabbix_agentd.conf.d/"
ZAF_AGENT_CONFIG="/etc/zabbix_agentd.conf" ZAF_AGENT_CONFIG="/etc/zabbix_agentd.conf"
ZAF_AGENT_PKG="zabbix-agentd" ZAF_AGENT_PKG="zabbix-agentd"
ZAF_CURL_INSECURE=1 ZAF_CURL_INSECURE=1
} }
zaf_configure_os_beesip() { zaf_preconfigure_os_beesip() {
zaf_configure_os_openwrt zaf_preconfigure_os_openwrt
} }
zaf_configure_os_freebsd() { zaf_preconfigure_os_freebsd() {
ZAF_AGENT_PKG="zabbix3-agent" ZAF_AGENT_PKG="zabbix3-agent"
ZAF_AGENT_CONFIG="/usr/local/etc/zabbix3/zabbix_agentd.conf" ZAF_AGENT_CONFIG="/usr/local/etc/zabbix3/zabbix_agentd.conf"
ZAF_AGENT_CONFIGD="/usr/local/etc/zabbix3/zabbix_agentd.conf.d/" ZAF_AGENT_CONFIGD="/usr/local/etc/zabbix3/zabbix_agentd.conf.d/"
ZAF_AGENT_BIN="/usr/local/sbin/zabbix_agentd" ZAF_AGENT_BIN="/usr/local/sbin/zabbix_agentd"
ZAF_AGENT_RESTART="service zabbix_agentd restart" ZAF_AGENT_RESTART="service zabbix_agentd restart"
ZAF_SUDOERSD="/usr/local/etc/sudoers.d" ZAF_SUDOERSD="/usr/local/etc/sudoers.d"
}
zaf_postconfigure_os_openwrt() {
if ! grep -q "zaf agent-config" /etc/init.d/zabbix_agentd; then
sed -i 's/uci2config $NAME/uci2config $NAME; zaf agent-config/' /etc/init.d/zabbix_agentd
fi
}
zaf_postconfigure_os_beesip() {
zaf_postconfigure_os_openwrt
}
zaf_which() {
if which >/dev/null 2>/dev/null; then
which "$1"
else
for i in /bin /sbin /usr/bin /usr/sbin /usr/local/bin /usr/local/sbin; do
[ -x $i/$1 ] && { echo $i/$1; return; }
done
return 1
fi
} }
zaf_detect_system() { zaf_detect_system() {
ZAF_FILES_UID=zabbix ZAF_FILES_UID=zabbix
ZAF_FILES_GID=zabbix ZAF_FILES_GID=zabbix
ZAF_FILES_UMASK=0770 ZAF_FILES_UMASK=0770
if which dpkg >/dev/null; then if zaf_which dpkg >/dev/null; then
ZAF_PKG=dpkg ZAF_PKG=dpkg
ZAF_OS=$(lsb_release -is|zaf_tolower) ZAF_OS=$(lsb_release -is|zaf_tolower)
ZAF_OS_CODENAME=$(lsb_release -cs|zaf_tolower) ZAF_OS_CODENAME=$(lsb_release -cs|zaf_tolower)
ZAF_CURL_INSECURE=0 ZAF_CURL_INSECURE=0
ZAF_AGENT_PKG="zabbix-agent" ZAF_AGENT_PKG="zabbix-agent"
return return
else if which rpm >/dev/null; then else if zaf_which rpm >/dev/null; then
ZAF_PKG="rpm" ZAF_PKG="rpm"
ZAF_OS=$(lsb_release -is|zaf_tolower) ZAF_OS=$(lsb_release -is|zaf_tolower)
ZAF_OS_CODENAME=$(lsb_release -cs|zaf_tolower) ZAF_OS_CODENAME=$(lsb_release -cs|zaf_tolower)
ZAF_CURL_INSECURE=0 ZAF_CURL_INSECURE=0
ZAF_AGENT_PKG="zabbix-agent" ZAF_AGENT_PKG="zabbix-agent"
return return
else if which opkg >/dev/null; then else if zaf_which opkg >/dev/null; then
ZAF_PKG="opkg" ZAF_PKG="opkg"
. /etc/openwrt_release . /etc/openwrt_release
ZAF_OS="$(echo $DISTRIB_ID|zaf_tolower)" ZAF_OS="$(echo $DISTRIB_ID|zaf_tolower)"
ZAF_OS_CODENAME="$(echo $DISTRIB_CODENAME|zaf_tolower)" ZAF_OS_CODENAME="$(echo $DISTRIB_CODENAME|zaf_tolower)"
return return
else if which pkg >/dev/null; then else if zaf_which pkg >/dev/null; then
ZAF_PKG="pkg" ZAF_PKG="pkg"
ZAF_OS="freebsd" ZAF_OS="freebsd"
ZAF_OS_CODENAME="$(freebsd-version|cut -d '-' -f 1)" ZAF_OS_CODENAME="$(freebsd-version|cut -d '-' -f 1)"
@@ -54,9 +75,9 @@ zaf_detect_system() {
ZAF_OS="unknown" ZAF_OS="unknown"
ZAF_OS_CODENAME="unknown" ZAF_OS_CODENAME="unknown"
ZAF_AGENT_PKG="" ZAF_AGENT_PKG=""
return return
fi fi
fi fi
fi fi
fi fi
} }
@@ -65,79 +86,70 @@ zaf_detect_system() {
# $1 - name of the function. # $1 - name of the function.
# all variants will be tested. (name_os_codename, name_os, name_{dpkg|opkg|rpm}, name ) # all variants will be tested. (name_os_codename, name_os, name_{dpkg|opkg|rpm}, name )
zaf_os_specific(){ zaf_os_specific(){
local func="$1" local func="$1"
if type "${func}_${ZAF_OS}_${ZAF_OS_CODENAME}" >/dev/null 2>/dev/null; then if type "${func}_${ZAF_OS}_${ZAF_OS_CODENAME}" >/dev/null 2>/dev/null; then
eval "${func}_${ZAF_OS}_${ZAF_OS_CODENAME} $2 $3 $4 $5 $6" eval "${func}_${ZAF_OS}_${ZAF_OS_CODENAME} $2 $3 $4 $5 $6"
else if type "${func}_${ZAF_OS}" >/dev/null 2>/dev/null; then else if type "${func}_${ZAF_OS}" >/dev/null 2>/dev/null; then
eval "${func}_${ZAF_OS} $2 $3 $4 $5 $6" eval "${func}_${ZAF_OS} $2 $3 $4 $5 $6"
else if type "${func}_${ZAF_PKG}" >/dev/null 2>/dev/null; then else if type "${func}_${ZAF_PKG}" >/dev/null 2>/dev/null; then
eval "${func}_${ZAF_PKG} $2 $3 $4 $5 $6" eval "${func}_${ZAF_PKG} $2 $3 $4 $5 $6"
else else
zaf_dbg "No OS/packager specific implementation for $1" zaf_dbg "No OS/packager specific implementation for $1"
fi fi
fi fi
fi fi
} }
zaf_is_root(){ zaf_is_root(){
[ "$USER" = "root" ] [ "$USER" = "root" ] || [ "$EUID" = "0" ] || [ -n "$ZAF_ISROOT" ]
} }
# Install file, bin or directory and respect install prefix # Install file, bin or directory and respect install prefix
# $1 - src file # $1 - src file
# $2 - directory # $2 - directory
zaf_install(){ zaf_install(){
zaf_dbg "Install file $1 to $INSTALL_PREFIX/$2/$(basename $1)" zaf_dbg "Install file $1 to $INSTALL_PREFIX/$2/$(basename $1)"
$ZAF_DO cp "$1" "$INSTALL_PREFIX/$2/$(basename $1)" $ZAF_DO cp "$1" "$INSTALL_PREFIX/$2/$(basename $1)" || zaf_err "Cannot create file $INSTALL_PREFIX/$2/$(basename $1)!"
} }
# $1 - src file # $1 - src file
# $2 - directory # $2 - directory
zaf_install_bin(){ zaf_install_bin(){
zaf_dbg "Install binary $1 to $INSTALL_PREFIX/$2/$(basename $1)" zaf_dbg "Install binary $1 to $INSTALL_PREFIX/$2/$(basename $1)"
$ZAF_DO cp "$1" "$INSTALL_PREFIX/$2/$(basename $1)" $ZAF_DO cp "$1" "$INSTALL_PREFIX/$2/$(basename $1)" || zaf_err "Cannot create binary $INSTALL_PREFIX/$2/$(basename $1)!"
$ZAF_DO chmod +x "$INSTALL_PREFIX/$2/$(basename $1)" $ZAF_DO chmod +x "$INSTALL_PREFIX/$2/$(basename $1)"
} }
# $1 - directory # $1 - directory
zaf_install_dir(){ zaf_install_dir(){
zaf_dbg "Install directory $1 to $INSTALL_PREFIX/$1" zaf_dbg "Install directory $1 to $INSTALL_PREFIX/$1"
$ZAF_DO mkdir -p "$INSTALL_PREFIX/$1" $ZAF_DO mkdir -p "$INSTALL_PREFIX/$1" || zaf_err "Cannot create directory $INSTALL_PREFIX/$1!"
} }
# $1 - file # $1 - file
zaf_touch(){ zaf_touch(){
zaf_dbg "Touch $INSTALL_PREFIX/$1" zaf_dbg "Touch $INSTALL_PREFIX/$1"
$ZAF_DO touch "$INSTALL_PREFIX/$1" $ZAF_DO touch "$INSTALL_PREFIX/$1"
} }
# $1 - directory # $1 - directory
zaf_uninstall(){ zaf_uninstall(){
if [ -n "$INSTALL_PREFIX" ]; then if [ -n "$INSTALL_PREFIX" ]; then
zaf_dbg "Removing $INSTALL_PREFIX/$1" zaf_dbg "Removing $INSTALL_PREFIX/$1"
$ZAF_DO rm -rf "$INSTALL_PREFIX/$1" $ZAF_DO rm -rf "$INSTALL_PREFIX/$1"
else else
zaf_dbg "Removing $1" zaf_dbg "Removing $1"
$ZAF_DO rm -rf "$1" $ZAF_DO rm -rf "$1"
fi fi
}
# Automaticaly install agent on debian
# For another os, create similar function (install_zabbix_centos)
zaf_install_agent_debian() {
zaf_fetch_url "http://repo.zabbix.com/zabbix/3.0/debian/pool/main/z/zabbix-release/zabbix-release_3.0-1+${ZAF_OS_CODENAME}_all.deb" >"/tmp/zaf-installer/zabbix-release_3.0-1+${ZAF_OS_CODENAME}_all.deb" \
&& dpkg -i "/tmp/zaf-installer/zabbix-release_3.0-1+${ZAF_OS_CODENAME}_all.deb" \
&& apt-get update \
&& apt-get install -y -q $ZAF_AGENT_PKG
} }
zaf_install_agent_opkg() { zaf_install_agent_opkg() {
opkg update && \ opkg update && \
opkg install $ZAF_AGENT_PKG opkg install $ZAF_AGENT_PKG
} }
# Check if dpkg dependency is met # Check if dpkg dependency is met
# $* - packages # $* - packages
zaf_check_deps_dpkg() { zaf_check_deps_dpkg() {
for i in $*; do for i in $*; do
dpkg-query -f '${Status},${Package}\n' -W $* 2>/dev/null | grep -q "^install ok installed" dpkg-query -f '${db:Status-Status},${Package}\n' -W $* 2>/dev/null | grep -qE "^(installed|^,)"
done done
} }

View File

@@ -18,24 +18,16 @@ zaf_update_repo() {
zaf_get_plugin_url() { zaf_get_plugin_url() {
local url local url
if echo "$1" | grep -q '/'; then if [ "$(zaf_url_info $1)" = "path" ]; then
url="$1" # plugin with path - from directory url="$1" # plugin with path - from directory
else else
if echo "$1" | grep -q ^http; then if [ "$(zaf_url_info $1)" = "url" ]; then
url="$1" # plugin with http[s] url url="$1" # plugin with http[s] url
else else
if [ -d "${ZAF_REPO_DIR}/$1" ]; then if [ -n "${ZAF_REPO_URL}" ]; then
url="${ZAF_REPO_DIR}/$1" url="${ZAF_REPO_URL}/$1"
else else
if [ -n "${ZAF_PREPACKAGED_DIR}" ] && [ -d "${ZAF_PREPACKAGED_DIR}/$1" ]; then zaf_err "Cannot find plugin $1"
url="${ZAF_PREPACKAGED_DIR}/$1"
else
if [ -n "${ZAF_REPO_URL}" ]; then
url="${ZAF_REPO_URL}/$1"
else
zaf_err "Cannot find plugin $1"
fi
fi
fi fi
fi fi
fi fi
@@ -48,13 +40,15 @@ zaf_plugin_info() {
local items local items
! [ -f "$control" ] && zaf_err "Control file $control not found." ! [ -f "$control" ] && zaf_err "Control file $control not found."
plugin=$(zaf_ctrl_get_global_block <"${control}" | zaf_block_get_option Plugin) plugin=$(zaf_ctrl_get_global_option "${control}" Plugin)
pdescription=$(zaf_ctrl_get_global_block <"${control}" | zaf_block_get_moption Description) pdescription=$(zaf_ctrl_get_global_option "${control}" Description)
pmaintainer=$(zaf_ctrl_get_global_block <"${control}" | zaf_block_get_option Maintainer) pmaintainer=$(zaf_ctrl_get_global_option "${control}" Maintainer)
pversion=$(zaf_ctrl_get_global_block <"${control}" | zaf_block_get_option Version) pversion=$(zaf_ctrl_get_global_option "${control}" Version)
purl=$(zaf_ctrl_get_global_block <"${control}" | zaf_block_get_option Url) purl=$(zaf_ctrl_get_global_option "${control}" Url)
phome=$(zaf_ctrl_get_global_block <"${control}" | zaf_block_get_option Home) phome=$(zaf_ctrl_get_global_option "${control}" Home)
pitems=$(zaf_ctrl_get_items <"${control}") pitems=$(zaf_ctrl_get_items <"${control}")
peitems=$(zaf_ctrl_get_extitems <"${control}")
params=$(zaf_ctrl_get_global_option "${control}" Parameters)
echo echo
echo -n "Plugin '$plugin' "; [ -n "$pversion" ] && echo -n "version ${pversion}"; echo ":" echo -n "Plugin '$plugin' "; [ -n "$pversion" ] && echo -n "version ${pversion}"; echo ":"
echo "$pdescription"; echo echo "$pdescription"; echo
@@ -64,17 +58,47 @@ zaf_plugin_info() {
echo echo
if zaf_is_plugin "$(basename $plugin)"; then if zaf_is_plugin "$(basename $plugin)"; then
items=$(zaf_list_plugin_items $plugin) items=$(zaf_list_plugin_items $plugin)
[ -n "$items" ] && echo -n "Defined items: "; echo $items if [ -n "$params" ]; then
printf "%b" "Plugin parameters: (name,default,actual value)\n"
zaf_ctrl_get_global_option "${control}" Parameters | while read param default ; do
printf "%b" "$param\t$default\t$(zaf_get_plugin_parameter $(dirname $1) $param)\n"
done
echo;
fi
[ -n "$items" ] && { echo -n "Defined items: "; echo $items; }
items=$(zaf_list_plugin_items $plugin test) items=$(zaf_list_plugin_items $plugin test)
[ -n "$items" ] && echo -n "Test items: "; echo $items [ -n "$items" ] && { echo -n "Test items: "; echo $items; }
items=$(zaf_list_plugin_items $plugin precache) items=$(zaf_list_plugin_items $plugin precache)
[ -n "$items" ] && echo -n "Precache items: "; echo $items [ -n "$items" ] && { echo -n "Precache items: "; echo $items; }
[ -n "$peitems" ] && { echo -n "External check items: "; echo $peitems; }
else else
echo "Items: $pitems" echo "Items: $pitems"
fi fi
echo echo
} }
# Get global plugin parameters
# $1 plugin
zaf_get_plugin_parameters() {
zaf_ctrl_get_global_option "${ZAF_PLUGINS_DIR}/${p}/control.zaf" "Parameters" | while read param rest; do echo $param; done
}
# Set plugin global parameter
# $1 plugindir
# $2 parameter
# $3 value
zaf_set_plugin_parameter() {
printf "%s" "$3" >"${INSTALL_PREFIX}/${1}/${2}.value"
}
# Get plugin global parameter
# $1 plugindir
# $2 parameter
zaf_get_plugin_parameter() {
[ -f "${1}/${2}.value" ] && cat "${1}/${2}.value"
}
# Prepare plugin into dir # Prepare plugin into dir
# $1 is url, directory or plugin name (will be searched in default plugin dir). # $1 is url, directory or plugin name (will be searched in default plugin dir).
# $2 is directory to prepare. # $2 is directory to prepare.
@@ -82,16 +106,24 @@ zaf_prepare_plugin() {
local url local url
local plugindir local plugindir
local control local control
local pluginname
url=$(zaf_get_plugin_url "$1")/control.zaf || exit $? url=$(zaf_get_plugin_url "$1")/control.zaf || exit $?
plugindir="$2" plugindir="$2"
control=${plugindir}/control.zaf control=${plugindir}/control.zaf
if [ "$(zaf_url_info $1)" = "path" ] && [ "$url" = "$control" ]; then
zaf_err "prepare_plugin: Cannot install from itself ($url,$control)!"
fi
zaf_install_dir "$plugindir" zaf_install_dir "$plugindir"
zaf_dbg "Fetching control file from $url ..." zaf_dbg "Fetching control file from $url ..."
if zaf_fetch_url "$url" >"${control}"; then if zaf_fetch_url "$url" >"${INSTALL_PREFIX}/${control}" && [ -s "${INSTALL_PREFIX}/${control}" ]; then
zaf_ctrl_check_deps "${control}" [ -z "${INSTALL_PREFIX}" ] && zaf_ctrl_check_deps "${control}"
pluginname=$(zaf_ctrl_get_global_block <"${INSTALL_PREFIX}/${control}" | zaf_block_get_option Plugin)
[ "$(basename $plugindir)" != "$pluginname" ] && zaf_err "prepare_plugin: Plugin name mismach ($plugindir vs ${INSTALL_PREFIX}/${control})!"
true
else else
zaf_err "prepare_plugin: Cannot fetch or write control file $control from url $url!" rm -rf "$plugindir"
zaf_err "prepare_plugin: Cannot fetch or write control file ${INSTALL_PREFIX}/$control from url $url!"
fi fi
} }
@@ -99,35 +131,78 @@ zaf_install_plugin() {
local url local url
local plugin local plugin
local plugindir local plugindir
local tmpplugindir
local control local control
local version local version
local eparam
local param
local default
if zaf_prepare_plugin "$1" "${ZAF_TMP_DIR}/plugin"; then plugin=$(basename "$1")
plugindir="${ZAF_PLUGINS_DIR}/${plugin}"
if [ -n "$plugin" ] && zaf_prepare_plugin "$1" $plugindir; then
url=$(zaf_get_plugin_url "$1") url=$(zaf_get_plugin_url "$1")
control="${ZAF_TMP_DIR}/plugin/control.zaf" zaf_wrn "Installing plugin $plugin"
plugin=$(zaf_ctrl_get_global_option $control Plugin) zaf_dbg "Source url: $url, Destination dir: $plugindir"
version=$(zaf_ctrl_get_global_option $control Version) control=${plugindir}/control.zaf
plugindir="${ZAF_PLUGINS_DIR}"/$plugin [ "$ZAF_DEBUG" -gt 1 ] && zaf_plugin_info "${control}"
if [ -n "$plugin" ] && zaf_prepare_plugin "$1" $plugindir; then if [ -z "${INSTALL_PREFIX}" ]; then
zaf_wrn "Installing plugin $plugin version $version"
zaf_dbg "Source url: $url, Destination dir: $plugindir"
control=${plugindir}/control.zaf
[ "$ZAF_DEBUG" -gt 1 ] && zaf_plugin_info "${control}"
zaf_ctrl_check_deps "${control}" zaf_ctrl_check_deps "${control}"
zaf_ctrl_sudo "$plugin" "${control}" "${plugindir}" zaf_ctrl_sudo "$plugin" "${control}" "${plugindir}"
zaf_ctrl_cron "$plugin" "${control}" "${plugindir}" zaf_ctrl_cron "$plugin" "${control}" "${plugindir}"
zaf_ctrl_generate_cfg "${control}" "${plugin}" \ zaf_ctrl_generate_items_cfg "${control}" "${plugin}" \
| zaf_far '{PLUGINDIR}' "${plugindir}" >${ZAF_AGENT_CONFIGD}/zaf_${plugin}.conf | zaf_far '{PLUGINDIR}' "${plugindir}" >${ZAF_AGENT_CONFIGD}/zaf_${plugin}.conf
zaf_dbg "Generated ${ZAF_AGENT_CONFIGD}/zaf_${plugin}.conf" zaf_dbg "Generated ${ZAF_AGENT_CONFIGD}/zaf_${plugin}.conf"
zaf_ctrl_install "$url" "${control}" "${plugindir}" zaf_ctrl_generate_extitems_cfg "${control}" "${plugin}"
else else
zaf_err "Cannot install plugin '$plugin' to $plugindir!" zaf_touch "${plugindir}/postinst.need"
fi fi
else zaf_ctrl_install "$url" "${control}" "${plugindir}"
zaf_err "Cannot prepare plugin $1" rm -f "${plugindir}/params"
zaf_touch "${plugindir}/params"
(zaf_ctrl_get_global_option "${control}" "Parameters"; echo) | \
while read param default; do
[ -z "$param" ] && continue
echo $param >>"${plugindir}/params"
eval eparam=\$ZAF_${plugin}_${param}
if [ -z "$eparam" ] && ! zaf_get_plugin_parameter "$plugindir" "$param" >/dev/null; then
zaf_wrn "Do not forget to set parameter $param. Use zaf plugin-set $plugin $param value. Default is $default."
zaf_set_plugin_parameter "$plugindir" "$param" "$default"
else
if [ -n "$eparam" ]; then
zaf_dbg "Setting $param to $eparam from env."
zaf_set_plugin_parameter "$plugindir" "$param" "$eparam"
fi
fi
done
else
zaf_err "Cannot install plugin '$plugin' to $plugindir!"
fi fi
} }
zaf_postinstall_plugin() {
local url
local plugin
local plugindir
local tmpplugindir
local control
local version
plugin=$(basename "$1")
plugindir="${ZAF_PLUGINS_DIR}/${plugin}"
control=${plugindir}/control.zaf
[ "$ZAF_DEBUG" -gt 1 ] && zaf_plugin_info "${control}"
zaf_ctrl_check_deps "${control}"
zaf_ctrl_sudo "$plugin" "${control}" "${plugindir}"
zaf_ctrl_cron "$plugin" "${control}" "${plugindir}"
zaf_ctrl_generate_items_cfg "${control}" "${plugin}" \
| zaf_far '{PLUGINDIR}' "${plugindir}" >${ZAF_AGENT_CONFIGD}/zaf_${plugin}.conf
zaf_dbg "Generated ${ZAF_AGENT_CONFIGD}/zaf_${plugin}.conf"
zaf_ctrl_generate_extitems_cfg "${control}" "${plugin}"
}
# List installed plugins # List installed plugins
# $1 - plugin # $1 - plugin
zaf_list_plugins() { zaf_list_plugins() {
@@ -143,6 +218,17 @@ zaf_is_plugin() {
false false
} }
zaf_is_item() {
local plugin
local item
plugin=$(echo $1|cut -d '.' -f 1)
item=$(echo $1|cut -d '.' -f 2- | cut -d '[' -f 1)
[ -z "$plugin" ] || [ -z "$item" ] && return 1
zaf_is_plugin "$plugin" && zaf_list_plugin_items "$plugin" | grep -qE "\.(${item}\$|${item}\[)"
}
zaf_discovery_plugins() { zaf_discovery_plugins() {
zaf_list_plugins | zaf_discovery '{#PLUGIN}' zaf_list_plugins | zaf_discovery '{#PLUGIN}'
} }
@@ -228,23 +314,73 @@ zaf_list_plugin_items() {
echo echo
} }
zaf_list_plugin_commands() {
local plugindir
local commands
if ! zaf_is_plugin "$1"; then
zaf_err "Missing plugin name or plugin $1 unknown. ";
fi
plugindir="${ZAF_PLUGINS_DIR}/$1"
commands=$(zaf_ctrl_get_global_option "${plugindir}/control.zaf" Install-cmd)
if [ -n "$commands" ]; then
echo $commands;
else
zaf_wrn "Plugin $1 has no commands."
fi
}
# $1 plugin
# $2 cmd
# $3...$9 arguments
zaf_plugin_run_command() {
local plugin
local cmd
local args
plugin=$1
cmd=$2
args="$3 $4 $5 $6 $7 $8 $9"
if ! zaf_is_plugin "$plugin"; then
zaf_err "Missing plugin name or plugin $olugin unknown. ";
fi
plugindir="${ZAF_PLUGINS_DIR}/$plugin"
commands=$(zaf_ctrl_get_global_option "${plugindir}/control.zaf" Install-cmd)
if echo $commands |grep -q $cmd; then
export PATH=$plugindir:$PATH
cd $plugindir
[ -f functions.sh ] && source functions.sh
exec $cmd $args;
else
zaf_err "Plugin $1 has no command $cmd"
fi
}
zaf_item_info() { zaf_item_info() {
local plugin local plugin
local item local item
local param local param
local tmp
plugin=$(echo $1 | cut -d '.' -f 1) plugin=$(echo $1 | cut -d '.' -f 1)
item=$(echo $1 | cut -d '.' -f 2-) item=$(echo $1 | cut -d '.' -f 2-)
if zaf_is_plugin $plugin; then if zaf_is_plugin $plugin; then
if zaf_ctrl_get_items <$ZAF_PLUGINS_DIR/$plugin/control.zaf | grep -wq "$item"; then if zaf_ctrl_get_items <$ZAF_PLUGINS_DIR/$plugin/control.zaf | grep -wq "$item"; then
echo "Item $1:" printf "%b" "Item $1\n\n"
echo -n "Cache: "; zaf_ctrl_get_item_option $ZAF_PLUGINS_DIR/$plugin/control.zaf "$item" "Cache"; echo tmp=$(zaf_ctrl_get_item_option $ZAF_PLUGINS_DIR/$plugin/control.zaf "$item" "Cache")
echo "Parameters:" [ -n "$tmp" ] && printf "%b" "Cache: $tmp \n\n"
zaf_ctrl_get_item_option $ZAF_PLUGINS_DIR/$plugin/control.zaf "$item" "Parameters" ; echo tmp=$(zaf_ctrl_get_item_option $ZAF_PLUGINS_DIR/$plugin/control.zaf "$item" "Parameters")
echo "Testparameters:" [ -n "$tmp" ] && printf "%b" "Parameters:\n$tmp\n\n"
zaf_ctrl_get_item_option $ZAF_PLUGINS_DIR/$plugin/control.zaf "$item" "Testparameters"; echo tmp=$(zaf_ctrl_get_item_option $ZAF_PLUGINS_DIR/$plugin/control.zaf "$item" "Return")
echo "Precache:" [ -n "$tmp" ] && printf "%b" "Return: $tmp\n\n"
zaf_ctrl_get_item_option $ZAF_PLUGINS_DIR/$plugin/control.zaf "$item" "Precache"; echo tmp=$(zaf_ctrl_get_item_option $ZAF_PLUGINS_DIR/$plugin/control.zaf "$item" "Return-null")
[ -n "$tmp" ] && printf "%b" "Return-null: $tmp\n\n"
tmp=$(zaf_ctrl_get_item_option $ZAF_PLUGINS_DIR/$plugin/control.zaf "$item" "Return-empty")
[ -n "$tmp" ] && printf "%b" "Return-empty: $tmp\n\n"
tmp=$(zaf_ctrl_get_item_option $ZAF_PLUGINS_DIR/$plugin/control.zaf "$item" "Testparameters")
[ -n "$tmp" ] && printf "%b" "Testparameters: $tmp\n\n"
tmp=$(zaf_ctrl_get_item_option $ZAF_PLUGINS_DIR/$plugin/control.zaf "$item" "Precache")
[ -n "$tmp" ] && printf "%b" "Precache: $tmp\n\n"
grep "UserParameter=$1" $ZAF_AGENT_CONFIGD/zaf_${plugin}.conf grep "UserParameter=$1" $ZAF_AGENT_CONFIGD/zaf_${plugin}.conf
else else
zaf_err "No such item $item." zaf_err "No such item $item."
@@ -281,8 +417,17 @@ zaf_test_item() {
fi fi
} }
zaf_run_item() {
local item
item=$(echo $1| cut -d '[' -f 1)
params=$(echo $1| cut -d '[' -f 2- | tr ',' ' '| tr -d ']')
cmd=$(grep "^UserParameter=$item" $ZAF_AGENT_CONFIGD/zaf*.conf | cut -d ',' -f 2-)
echo $cmd >/tmp/a
sh /tmp/a $params
}
zaf_precache_item() { zaf_precache_item() {
cmd=$(grep "^UserParameter=$item" $ZAF_AGENT_CONFIGD/zaf*.conf | cut -d ',' -f 2- | sed -e "s/_cache/_nocache/") cmd=$(grep "^UserParameter=$item" $ZAF_AGENT_CONFIGD/zaf*.conf | cut -d ',' -f 2- | sed -e "s/_cache/_nocache/")
zaf_wrn "Precaching item $item[$(echo $*| tr ' ' ',')] ($cmd)" zaf_wrn "Precaching item $item[$(echo $*| tr ' ' ',')] ($cmd)"
eval $cmd eval $cmd
} }

View File

@@ -9,17 +9,23 @@
. ${ZAF_LIB_DIR}/zbxapi.lib.sh . ${ZAF_LIB_DIR}/zbxapi.lib.sh
. ${ZAF_LIB_DIR}/cache.lib.sh . ${ZAF_LIB_DIR}/cache.lib.sh
# Plugin specific functions if exists
[ -f ./functions.sh ] && . ./functions.sh
if ! type zaf_version >/dev/null; then if ! type zaf_version >/dev/null; then
echo "Problem loading libraries?" echo "Problem loading libraries?"
exit 2 exit 2
fi fi
zaf_debug_init zaf_debug_init
zaf_tmp_init zaf_tmp_init
zaf_cache_init zaf_cache_init
# Global plugin parameters
[ -f ./params ] && for p in $(cat ./params); do
var=$p
value="$(cat ${p}.value)"
zaf_trc "Global $p parameter $var=$value"
eval export $var="$value"
done
export ZAF_LIB_DIR export ZAF_LIB_DIR
export ZAF_TMP_DIR export ZAF_TMP_DIR
export ZAF_CACHE_DIR export ZAF_CACHE_DIR
@@ -28,10 +34,17 @@ export ZAF_DEBUG
unset ZAF_LOG_STDERR unset ZAF_LOG_STDERR
export PATH export PATH
# Plugin specific functions if exists
[ -f ./functions.sh ] && . ./functions.sh
if [ "$(basename $0)" = "preload.sh" ] && [ -n "$*" ]; then if [ "$(basename $0)" = "preload.sh" ] && [ -n "$*" ]; then
tmpf=$(zaf_tmpfile preload) tmpf=$(zaf_tmpfile preload)
export tmpf
$@ 2>$tmpf $@ 2>$tmpf
[ -s $tmpf ] && zaf_wrn <$tmpf [ -s $tmpf ] && zaf_wrn <$tmpf
else
tmpf=$(zaf_tmpfile preload)
export tmpf
fi fi

View File

@@ -1,7 +1,7 @@
# Hardcoded variables # Hardcoded variables
ZAF_VERSION="1.2" ZAF_VERSION="1.4"
ZAF_GITBRANCH="1.2" ZAF_GITBRANCH="master"
ZAF_URL="https://github.com/limosek/zaf" ZAF_URL="https://github.com/limosek/zaf"
ZAF_RAW_URL="https://raw.githubusercontent.com/limosek/zaf" ZAF_RAW_URL="https://raw.githubusercontent.com/limosek/zaf"
@@ -12,17 +12,20 @@ zaf_msg() {
} }
zaf_trc() { zaf_trc() {
[ "$ZAF_DEBUG" -ge "3" ] && logger -p user.info ${ZAF_LOG_STDERR} -t zaf-trace -- $@ [ "$ZAF_DEBUG" -ge "3" ] && logger -p user.info ${ZAF_LOG_STDERR} -t zaf-trace -- $@
return 0
} }
zaf_dbg() { zaf_dbg() {
[ "$ZAF_DEBUG" -ge "2" ] && logger -p user.debug ${ZAF_LOG_STDERR} -t zaf-debug -- $@ [ "$ZAF_DEBUG" -ge "2" ] && logger -p user.debug ${ZAF_LOG_STDERR} -t zaf-debug -- $@
return 0
} }
zaf_wrn() { zaf_wrn() {
[ "$ZAF_DEBUG" -ge "1" ] && logger -p user.warn ${ZAF_LOG_STDERR} -t zaf-warning -- $@ [ "$ZAF_DEBUG" -ge "1" ] && logger -p user.warn ${ZAF_LOG_STDERR} -t zaf-warning -- $@
return 0
} }
zaf_err() { zaf_err() {
logger ${ZAF_LOG_STDERR} -p user.err -t zaf-error -- $@ logger ${ZAF_LOG_STDERR} -p user.err -t zaf-error -- $@
logger ${ZAF_LOG_STDERR} -p user.err -t zaf-error "Exiting with error!" logger ${ZAF_LOG_STDERR} -p user.err -t zaf-error "Exiting with error!"
exit 1 exit 1
} }
# Help option # Help option
# $1 - key # $1 - key
@@ -72,11 +75,11 @@ zaf_agentparm(){
value="$default" value="$default"
else else
if [ -n "$regexp" ]; then if [ -n "$regexp" ]; then
echo "$value" | grep -qE "$regexp" || zaf_err "$ITEM_KEY: Bad parameter '$name' value '$value' (not in regexp '$regexp')." echo "$value" | grep -qE "$regexp" || zaf_err "$ITEM_KEY: Bad parameter '$name' value '$value' (not in regexp '$regexp')."
fi fi
fi fi
eval $name=$value
zaf_trc "$ITEM_KEY: Param $name set to $value" zaf_trc "$ITEM_KEY: Param $name set to $value"
eval $name=\"$value\"
} }
# Fetch url to stdout # Fetch url to stdout
@@ -99,50 +102,75 @@ zaf_fetch_url() {
case $scheme in case $scheme in
http|https|ftp|file) http|https|ftp|file)
[ "$scheme" != "file" ] && [ -n "$ZAF_OFFLINE" ] && zaf_err "Cannot download $1 in offline mode!" [ "$scheme" != "file" ] && [ -n "$ZAF_OFFLINE" ] && zaf_err "Cannot download $1 in offline mode!"
[ "${ZAF_CURL_INSECURE}" = "1" ] && insecure="-k" if zaf_which curl >/dev/null 2>/dev/null; then
zaf_dbg curl $insecure -f -s -L -o - $1 [ "${ZAF_CURL_INSECURE}" = "1" ] && insecure="-k"
curl $insecure -f -s -L -o - "$1" | zaf_tocache_stdin "$1" 120 zaf_dbg curl $insecure -f -s -L -o - $1
curl $insecure -f -s -L -o - "$1" | zaf_tocache_stdin "$1" 120
else
[ "${ZAF_CURL_INSECURE}" = "1" ] && insecure="--no-check-certificate"
zaf_dbg wget $insecure -O - $1
wget $insecure -O - "$1" | zaf_tocache_stdin "$1" 120
fi
;; ;;
esac esac
} }
# Get info about url
# returns path or url
zaf_url_info() {
if echo "$1" | grep -q '^/'; then
echo "path"
else
if echo "$1" | grep -q ^http; then
echo "url"
else
echo "unknown"
fi
fi
}
# Find and replace string # Find and replace string
zaf_far(){ zaf_far(){
local f local f
local t local t
local sedcmd="sed" local sedcmd="sed"
i=1 i=1
while [ "$i" -lt "$#" ]; while [ "$i" -lt "$#" ];
do do
eval f=\$${i} eval f=\$${i}
i=$(expr $i + 1) i=$(expr $i + 1)
eval t=\$${i} eval t=\$${i}
i=$(expr $i + 1) i=$(expr $i + 1)
sedcmd="$sedcmd -e 's~$f~$t~g'" sedcmd="$sedcmd -e 's~$f~$t~g'"
done done
eval $sedcmd eval $sedcmd
}
# Trim spaces and newlines from string
zaf_trim(){
tr -d '\n'
} }
# Limit concurrent processes or continue # Limit concurrent processes or continue
zaf_bglimit(){ zaf_bglimit(){
local maxbg local maxbg
local maxnumber local maxnumber
local cnumber local cnumber
[ -z "$BASH_VERSION" ] && { zaf_dbg "Job server not available. Use bash!"; return 1; } [ -z "$BASH_VERSION" ] && { zaf_dbg "Job server not available. Use bash!"; return 1; }
if [ $# -eq 0 ] ; then if [ $# -eq 0 ] ; then
maxbg=5 maxbg=5
else else
maxbg=$1 maxbg=$1
fi fi
maxnumber=$((0 + ${1:-0})) maxnumber=$((0 + ${1:-0}))
while true; do while true; do
cnumber=$(jobs | wc -l) cnumber=$(jobs | wc -l)
if [ $cnumber -lt $maxnumber ]; then if [ $cnumber -lt $maxnumber ]; then
break break
fi fi
zaf_dbg "Limiting next job due to $maxbg limit of bg jobs" zaf_dbg "Limiting next job due to $maxbg limit of bg jobs"
sleep 1 sleep 1
done done
} }
# Initialises discovery function # Initialises discovery function
@@ -155,27 +183,27 @@ EOF
# Add row(s) to discovery data # Add row(s) to discovery data
zaf_discovery_add_row(){ zaf_discovery_add_row(){
local rows local rows
local row local row
rows=$1 rows=$1
row=$2 row=$2
shift;shift shift;shift
echo " {" echo " {"
while [ -n "$1" ]; do while [ -n "$1" ]; do
echo -n ' "'$1'":"'$2'" ' echo -n ' "'$1'":"'$2'" '
shift;shift shift;shift
if [ -n "$1" ]; then if [ -n "$1" ]; then
echo "," echo ","
else else
echo "" echo ""
fi fi
done done
if [ "$row" -lt "$rows" ]; then if [ "$row" -lt "$rows" ]; then
echo " }," echo " },"
else else
echo " }" echo " }"
fi fi
} }
# Dumps json object # Dumps json object
@@ -190,22 +218,22 @@ EOF
# Arguments are name of variables to discovery. # Arguments are name of variables to discovery.
# Dumps json to stdout # Dumps json to stdout
zaf_discovery(){ zaf_discovery(){
local tmpfile local tmpfile
local rows local rows
local a b c d e f g h i j row local a b c d e f g h i j row
tmpfile="${ZAF_TMP_DIR}/disc$$" tmpfile="${ZAF_TMP_DIR}/disc$$"
cat >$tmpfile cat >$tmpfile
rows=$(wc -l <$tmpfile) rows=$(wc -l <$tmpfile)
local a b c d e f g h i j; local a b c d e f g h i j;
zaf_discovery_begin zaf_discovery_begin
row=1 row=1
while read a b c d e f g h i j; do while read a b c d e f g h i j; do
zaf_discovery_add_row "$rows" "$row" "$1" "${1:+${a}}" "$2" "${2:+${b}}" "$3" "${3:+${c}}" "$4" "${4:+${d}}" "$5" "${5:+${e}}" "$6" "${6:+${f}}" "$7" "${7:+${g}}" "$8" "${8:+${h}}" "$9" "${9:+${i}}" zaf_discovery_add_row "$rows" "$row" "$1" "${1:+${a}}" "$2" "${2:+${b}}" "$3" "${3:+${c}}" "$4" "${4:+${d}}" "$5" "${5:+${e}}" "$6" "${6:+${f}}" "$7" "${7:+${g}}" "$8" "${8:+${h}}" "$9" "${9:+${i}}"
row=$(expr $row + 1) row=$(expr $row + 1)
done <$tmpfile done <$tmpfile
zaf_discovery_end zaf_discovery_end
rm -f $tmpfile rm -f $tmpfile
} }
############################################ Zaf internal routines ############################################ Zaf internal routines
@@ -216,6 +244,12 @@ zaf_restart_agent() {
${ZAF_AGENT_RESTART} || zaf_err "Cannot restart Zabbix agent (${ZAF_AGENT_RESTART}). Try $ZAF_AGENT_BIN -f !"; ${ZAF_AGENT_RESTART} || zaf_err "Cannot restart Zabbix agent (${ZAF_AGENT_RESTART}). Try $ZAF_AGENT_BIN -f !";
} }
# Check if zaf.version item is populated
zaf_check_agent_config() {
zaf_restart_agent
${ZAF_AGENT_BIN} -t zaf.version
}
zaf_tolower() { zaf_tolower() {
tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'
} }
@@ -226,7 +260,7 @@ zaf_toupper() {
# Return simplified key with discarded special chars. # Return simplified key with discarded special chars.
zaf_stripctrl() { zaf_stripctrl() {
echo $1 | tr '[]*&;:.-' '________' echo $1 | tr '[]*&;:.-' '________' | tr -d '\n'
} }
# Unescape string on stdin # Unescape string on stdin
@@ -250,7 +284,7 @@ zaf_date_add() {
# Create temp file and return its name # Create temp file and return its name
# $1 prefix or empty # $1 prefix or empty
zaf_tmpfile() { zaf_tmpfile() {
echo "$ZAF_TMP_DIR/tmp$1" echo "$ZAF_TMP_DIR/tmp$1$(zaf_random)"
} }
# return random number # return random number
@@ -260,10 +294,63 @@ zaf_random() {
# Emulate sudo # Emulate sudo
zaf_sudo() { zaf_sudo() {
if zaf_is_root || ! which sudo >/dev/null 2>/dev/null; then if zaf_is_root || ! zaf_which sudo >/dev/null 2>/dev/null; then
$@ $@
else else
sudo $@ sudo $@
fi fi
} }
# Get item name from plugin.item[parms]
zaf_get_plugin_name() {
echo $1|cut -d '.' -f 1
}
# Get item name from plugin.item[parms]
zaf_get_item_name() {
echo $1|cut -d '.' -f 2-|cut -d '[' -f 1
}
# Get item params from plugin.item[parms]
zaf_get_item_params() {
echo $1|cut -d '[' -f 2|cut -d ']' -f 1
}
# Convert Zabbix style parameters [param1,param2,..] into $1 $2 $3
zaf_paramstosh() {
local parms
local IFS
parms=$(echo $*|cut -d '[' -f 2 | cut -d ']' -f 1| tr ',' '~')
IFS="~"; for i in $parms; do
if [ -n "$i" ]; then
printf "$i "
else
printf "'' "
fi
done
}
#Returns either actual hostname or configured one
zaf_hostname() {
if [ -z "$ZAF_HOSTNAME" ]; then
hostname
else
echo $ZAF_HOSTNAME
fi
}
# Send active agent query (used for auto registration of host)
# $1 hostname
# $2 metadata
zaf_register() {
local query
local result
zaf_dbg "zaf_register $1 $2"
query="{\"host\": \"$1\", \"host_metadata\": \"$2\", \"request\": \"active checks\"}"
result="$(echo $query| nc -q1 $ZAF_ZBXSRV_HOST $ZAF_ZBXSRV_PORT | tail -c +14)"
if echo $result |grep -q failed; then
zaf_wrn $result
fi
}

View File

@@ -19,16 +19,8 @@ else
fi fi
if ! zaf_fromcache "$key"; then if ! zaf_fromcache "$key"; then
zaf_fromcache "$key" >/dev/null 2>/dev/null tmpf=$(zaf_tmpfile cache)
[ $? -eq 3 ] && { zaf_err "Operation $key already in progress."; } $@ 2>"$tmpf" | zaf_tocache_stdin "$key" "$seconds"
if which at >/dev/null 2>/dev/null; then [ -s $tmpf ] && zaf_wrn <$tmpf
at -M now >/dev/null 2>/dev/null <<EOF
. $(dirname $0)/preload.sh; tmpf=\$(zaf_tmpfile cache); $@ 2>"\$tmpf" | zaf_tocache_stdin "$key" "$seconds" ; [ -s \$tmpf ] && zaf_wrn <\$tmpf
EOF
else
tmpf=$(zaf_tmpfile cache)
$@ 2>"$tmpf" | zaf_tocache_stdin "$key" "$seconds"
[ -s $tmpf ] && zaf_wrn <$tmpf
fi
fi fi

29
lib/zafext Normal file
View File

@@ -0,0 +1,29 @@
#!/bin/sh
. /etc/zaf.conf
. ${ZAF_LIB_DIR}/zaf.lib.sh
. ${ZAF_LIB_DIR}/plugin.lib.sh
. ${ZAF_LIB_DIR}/ctrl.lib.sh
. ${ZAF_LIB_DIR}/os.lib.sh
. ${ZAF_LIB_DIR}/zbxapi.lib.sh
. ${ZAF_LIB_DIR}/cache.lib.sh
if ! type zaf_version >/dev/null; then
echo "Problem loading libraries?"
exit 2
fi
zaf_debug_init
zaf_tmp_init
zaf_cache_init
export ZAF_LIB_DIR
export ZAF_TMP_DIR
export ZAF_CACHE_DIR
export ZAF_PLUGINS_DIR
export ZAF_DEBUG
unset ZAF_LOG_STDERR
export PATH
export ZAF_ITEM=$(basename $0)

52
lib/zafret Executable file
View File

@@ -0,0 +1,52 @@
#!/bin/sh
. $(dirname $0)/preload.sh
if [ -z "$1" ] || [ -z "$2" ] || [ -z "$3" ]; then
zaf_err "zafret valuefile stderrfile retcode [return return_if_null return_if_error]"
exit 1
fi
value="$(cat $1)"
rm -f $1
shift
stderr="$(cat $1)"
rm -f $1
shift
retcode="$1"
shift
if [ -n "$1" ]; then
ret="$1"
shift
fi
if [ -n "$1" ]; then
retnull="$1"
shift
fi
if [ -n "$1" ]; then
reterr="$1"
shift
fi
if [ "$retcode" != 0 ]; then
echo "$reterr"
zaf_wrn "${ITEM_KEY}("$*"): Error code '$retcode', returning '$reterr' ($stderr)"
exit $retcode
fi
if [ -z "$value" ]; then
echo "$retnull"
zaf_wrn "${ITEM_KEY}("$*"): Got empty result, returning '$retnull' ($stderr)"
exit
fi
echo $value
if [ -n "$stderr" ]; then
zaf_wrn "${ITEM_KEY}("$*"): $stderr"
fi

View File

@@ -10,7 +10,7 @@ zaf_zbxapi_do() {
query="$1" query="$1"
zaf_trc "Zabbix API: $query" zaf_trc "Zabbix API: $query"
curl -s -f -L -X POST -H 'Content-Type: application/json-rpc' -d "$query" "$ZAF_ZBXAPI_URL" >$tmpfile curl -s -f -L -X POST -H 'Content-Type: application/json-rpc' -d "$query" "$ZAF_ZBXAPI_URL" >$tmpfile
if [ $? = 0 ] && $ZAF_LIB_DIR/JSON.sh -b <$tmpfile | grep -q '"result"'; then if [ $? = 0 ] && $ZAF_LIB_DIR/JSON.sh -b <$tmpfile | grep -q '"result"'; then
zaf_trc "API OK" zaf_trc "API OK"
cat $tmpfile cat $tmpfile
rm -f $tmpfile rm -f $tmpfile
@@ -52,7 +52,7 @@ zaf_zbxapi_getstring() {
# Extract value from JSON response result # Extract value from JSON response result
# $1 key # $1 key
zaf_zbxapi_getvalues() { zaf_zbxapi_getvalues() {
$ZAF_LIB_DIR/JSON.sh -b | grep '\["result",.*,"'$1'"]' | tr '\t' ' ' | cut -d ' ' -f 2- | sed -e 's/^"//' -e 's/"$//' $ZAF_LIB_DIR/JSON.sh -b | grep '\["result",.*,"'$1'"]' | tr '\t' ' ' | cut -d ' ' -f 2- | sed -e 's/^"//' -e 's/"$//'
} }
# Zabbix API related functions # Zabbix API related functions
@@ -66,17 +66,17 @@ zaf_zbxapi_login(){
[ -z "$ZAF_ZBXAPI_URL" ] || [ -z "$ZAF_ZBXAPI_USER" ] || [ -z "$ZAF_ZBXAPI_PASS" ] && zaf_err "Zabbix Api parameters not set! Set ZAF_ZBXAPI_URL, ZAF_ZBXAPI_USER and ZAF_ZBXAPI_PASS and try again." [ -z "$ZAF_ZBXAPI_URL" ] || [ -z "$ZAF_ZBXAPI_USER" ] || [ -z "$ZAF_ZBXAPI_PASS" ] && zaf_err "Zabbix Api parameters not set! Set ZAF_ZBXAPI_URL, ZAF_ZBXAPI_USER and ZAF_ZBXAPI_PASS and try again."
authstr='{ authstr='{
"method" : "user.login", "method" : "user.login",
"params" : { "params" : {
"password" : "'$ZAF_ZBXAPI_PASS'", "password" : "'$ZAF_ZBXAPI_PASS'",
"user" : "'$ZAF_ZBXAPI_USER'" "user" : "'$ZAF_ZBXAPI_USER'"
}, },
"id" : 0, "id" : 0,
"jsonrpc" : "2.0" "jsonrpc" : "2.0"
}' }'
if [ "$ZAF_ZBXAPI_AUTHTYPE" = "http" ] ; then if [ "$ZAF_ZBXAPI_AUTHTYPE" = "http" ] ; then
ZAF_ZBXAPI_URL=$(echo $ZAF_ZBXAPI_URL | cut -d '/' -f 1)//$ZAF_ZBXAPI_USER:$ZAF_ZBXAPI_PASS@$(echo $ZAF_ZBXAPI_URL | cut -d '/' -f 3-) ZAF_ZBXAPI_URL=$(echo $ZAF_ZBXAPI_URL | cut -d '/' -f 1)//$ZAF_ZBXAPI_USER:$ZAF_ZBXAPI_PASS@$(echo $ZAF_ZBXAPI_URL | cut -d '/' -f 3-)
fi fi
result=$(zaf_zbxapi_do_cache "$authstr") result=$(zaf_zbxapi_do_cache "$authstr")
ZAF_ZBXAPI_AUTH=$(echo $result |zaf_zbxapi_getstring) ZAF_ZBXAPI_AUTH=$(echo $result |zaf_zbxapi_getstring)
@@ -122,9 +122,9 @@ zaf_zbxapi_get_object() {
zaf_zbxapi_gethostgroupid() { zaf_zbxapi_gethostgroupid() {
local result local result
result=$(zaf_zbxapi_get_object "hostgroup" '"name": ["'$1'"]') result=$(zaf_zbxapi_get_object "hostgroup" '"name": ["'$1'"]')
[ -z "$result" ] && zaf_err "HostGroup $1 not found!" [ -z "$result" ] && zaf_err "HostGroup $1 not found!"
echo $result |zaf_zbxapi_getvalues groupid echo $result |zaf_zbxapi_getvalues groupid
} }
# $1 hostid # $1 hostid
@@ -132,10 +132,10 @@ zaf_zbxapi_gethostgroupid() {
zaf_zbxapi_gethost() { zaf_zbxapi_gethost() {
local result local result
result=$(zaf_zbxapi_get_object "host" '' '"hostids": ["'$1'"]' 'extend') result=$(zaf_zbxapi_get_object "host" '' '"hostids": ["'$1'"]' 'extend')
[ -z "$result" ] && zaf_err "Hostid $1 not found!" [ -z "$result" ] && zaf_err "Hostid $1 not found!"
if [ -z "$2" ]; then if [ -z "$2" ]; then
echo $result echo $result
else else
echo $result |zaf_zbxapi_getvalues $2 echo $result |zaf_zbxapi_getvalues $2
fi fi
@@ -145,9 +145,9 @@ zaf_zbxapi_gethost() {
zaf_zbxapi_gethostid() { zaf_zbxapi_gethostid() {
local result local result
result=$(zaf_zbxapi_get_object "host" '"host": ["'$1'"]') result=$(zaf_zbxapi_get_object "host" '"host": ["'$1'"]')
[ -z "$result" ] && zaf_err "Host $1 not found!" [ -z "$result" ] && zaf_err "Host $1 not found!"
echo $result |zaf_zbxapi_getvalues hostid echo $result |zaf_zbxapi_getvalues hostid
} }
# $1 hostname # $1 hostname
@@ -155,10 +155,10 @@ zaf_zbxapi_gethostid() {
zaf_zbxapi_gethostinventory() { zaf_zbxapi_gethostinventory() {
local result local result
result=$(zaf_zbxapi_get_object "host" '"host": ["'$1'"]' '"withInventory": "true", "selectInventory": "extend"') result=$(zaf_zbxapi_get_object "host" '"host": ["'$1'"]' '"withInventory": "true", "selectInventory": "extend"')
[ -z "$result" ] && zaf_err "Host $1 not found!" [ -z "$result" ] && zaf_err "Host $1 not found!"
if [ -z "$2" ]; then if [ -z "$2" ]; then
echo $result echo $result
else else
echo $result |zaf_zbxapi_getvalues $2 echo $result |zaf_zbxapi_getvalues $2
fi fi
@@ -168,9 +168,9 @@ zaf_zbxapi_gethostinventory() {
zaf_zbxapi_gettemplateid() { zaf_zbxapi_gettemplateid() {
local result local result
result=$(zaf_zbxapi_get_object "template" '"host": ["'$1'"]') result=$(zaf_zbxapi_get_object "template" '"host": ["'$1'"]')
[ -z "$result" ] && zaf_err "Template $1 not found!" [ -z "$result" ] && zaf_err "Template $1 not found!"
echo $result |zaf_zbxapi_getvalues templateid echo $result |zaf_zbxapi_getvalues templateid
} }
# $1 templateid # $1 templateid
@@ -178,10 +178,10 @@ zaf_zbxapi_gettemplateid() {
zaf_zbxapi_gettemplate() { zaf_zbxapi_gettemplate() {
local result local result
result=$(zaf_zbxapi_get_object "template" '' '"templateids": ["'$1'"]' 'extend') result=$(zaf_zbxapi_get_object "template" '' '"templateids": ["'$1'"]' 'extend')
[ -z "$result" ] && zaf_err "Templateid $1 not found!" [ -z "$result" ] && zaf_err "Templateid $1 not found!"
if [ -z "$2" ]; then if [ -z "$2" ]; then
echo $result echo $result
else else
echo $result |zaf_zbxapi_getvalues $2 echo $result |zaf_zbxapi_getvalues $2
fi fi
@@ -191,34 +191,34 @@ zaf_zbxapi_gettemplate() {
zaf_zbxapi_gethostsingroup() { zaf_zbxapi_gethostsingroup() {
local result local result
result=$(zaf_zbxapi_get_object "host" '' '"groupids": ["'$1'"]') result=$(zaf_zbxapi_get_object "host" '' '"groupids": ["'$1'"]')
[ -z "$result" ] && zaf_wrn "No hosts in groupid '$1'" [ -z "$result" ] && zaf_wrn "No hosts in groupid '$1'"
echo $result | zaf_zbxapi_getvalues "hostid" echo $result | zaf_zbxapi_getvalues "hostid"
} }
# Get all hostids in system # Get all hostids in system
zaf_zbxapi_gethostids() { zaf_zbxapi_gethostids() {
local result local result
result=$(zaf_zbxapi_get_object "host") result=$(zaf_zbxapi_get_object "host")
echo $result | zaf_zbxapi_getvalues "hostid" echo $result | zaf_zbxapi_getvalues "hostid"
} }
# Get all templateids in system # Get all templateids in system
zaf_zbxapi_gettemplateids() { zaf_zbxapi_gettemplateids() {
local result local result
result=$(zaf_zbxapi_get_object "template") result=$(zaf_zbxapi_get_object "template")
echo $result | zaf_zbxapi_getvalues "templateid" echo $result | zaf_zbxapi_getvalues "templateid"
} }
# $1 hostgroupid # $1 hostgroupid
zaf_zbxapi_gettemplatesingroup() { zaf_zbxapi_gettemplatesingroup() {
local result local result
result=$(zaf_zbxapi_get_object "template" '' '"groupids": ["'$1'"]') result=$(zaf_zbxapi_get_object "template" '' '"groupids": ["'$1'"]')
[ -z "$result" ] && zaf_wrn "No templates in groupid '$1'" [ -z "$result" ] && zaf_wrn "No templates in groupid '$1'"
echo $result | zaf_zbxapi_getvalues "templateid" echo $result | zaf_zbxapi_getvalues "templateid"
} }
# $1 map or null for all # $1 map or null for all
@@ -226,12 +226,12 @@ zaf_zbxapi_getmapid() {
local result local result
if [ -n "$1" ]; then if [ -n "$1" ]; then
result=$(zaf_zbxapi_get_object "map" '"name": ["'$1'"]') result=$(zaf_zbxapi_get_object "map" '"name": ["'$1'"]')
else else
result=$(zaf_zbxapi_get_object "map") result=$(zaf_zbxapi_get_object "map")
fi fi
[ -z "$result" ] && zaf_err "Map $1 not found" [ -z "$result" ] && zaf_err "Map $1 not found"
echo $result | zaf_zbxapi_getvalues "sysmapid" echo $result | zaf_zbxapi_getvalues "sysmapid"
} }
# $1 mapid # $1 mapid
@@ -239,10 +239,10 @@ zaf_zbxapi_getmapid() {
zaf_zbxapi_getmap() { zaf_zbxapi_getmap() {
local result local result
result=$(zaf_zbxapi_get_object "map" '' '"sysmapids": ["'$1'"]' 'extend') result=$(zaf_zbxapi_get_object "map" '' '"sysmapids": ["'$1'"]' 'extend')
[ -z "$result" ] && zaf_err "Mapid $1 not found" [ -z "$result" ] && zaf_err "Mapid $1 not found"
if [ -z "$2" ]; then if [ -z "$2" ]; then
echo $result echo $result
else else
echo $result |zaf_zbxapi_getvalues $2 echo $result |zaf_zbxapi_getvalues $2
fi fi
@@ -261,18 +261,18 @@ zaf_zbxapi_export_object(){
bkpstr=' bkpstr='
{ {
"method": "configuration.export", "method": "configuration.export",
"jsonrpc": "2.0", "jsonrpc": "2.0",
"params": { "params": {
"options": { "options": {
"'$obj'": [ "'$obj'": [
"'$id'" "'$id'"
] ]
}, },
"format": "xml" "format": "xml"
}, },
"auth": "'$ZAF_ZBXAPI_AUTH'", "auth": "'$ZAF_ZBXAPI_AUTH'",
"id": 1 "id": 1
}' }'
zaf_zbxapi_do_cache "$bkpstr" | zaf_zbxapi_getxml zaf_zbxapi_do_cache "$bkpstr" | zaf_zbxapi_getxml
} }
@@ -303,67 +303,67 @@ zaf_zbxapi_import_config(){
local impstr local impstr
if [ -z "$1" ]; then if [ -z "$1" ]; then
xmlstr=$(zaf_strescape '"') xmlstr=$(zaf_strescape '"')
else else
! [ -f "$1" ] && return 1 ! [ -f "$1" ] && return 1
xmlstr=$(zaf_strescape '"\n\r' <$1) xmlstr=$(zaf_strescape '"\n\r' <$1)
fi fi
impstr=' impstr='
{ {
"method": "configuration.import", "method": "configuration.import",
"jsonrpc": "2.0", "jsonrpc": "2.0",
"params": { "params": {
"format": "xml", "format": "xml",
"rules": { "rules": {
"applications": { "applications": {
"createMissing": true, "createMissing": true,
"updateExisting": true "updateExisting": true
}, },
"discoveryRules": { "discoveryRules": {
"createMissing": true, "createMissing": true,
"updateExisting": true "updateExisting": true
}, },
"graphs": { "graphs": {
"createMissing": true, "createMissing": true,
"updateExisting": true "updateExisting": true
}, },
"hosts": { "hosts": {
"createMissing": true, "createMissing": true,
"updateExisting": true "updateExisting": true
}, },
"items": { "items": {
"createMissing": true, "createMissing": true,
"updateExisting": true "updateExisting": true
}, },
"templates": { "templates": {
"createMissing": true, "createMissing": true,
"updateExisting": true "updateExisting": true
}, },
"triggers": { "triggers": {
"createMissing": true, "createMissing": true,
"updateExisting": true "updateExisting": true
}, },
"maps": { "maps": {
"createMissing": true, "createMissing": true,
"updateExisting": true "updateExisting": true
}, },
"screens": { "screens": {
"createMissing": true, "createMissing": true,
"updateExisting": true "updateExisting": true
}, },
"items": { "items": {
"createMissing": true, "createMissing": true,
"updateExisting": true "updateExisting": true
}, },
"valueMaps": { "valueMaps": {
"createMissing": true, "createMissing": true,
"updateExisting": true "updateExisting": true
} }
}, },
"source": "'$xmlstr'" "source": "'$xmlstr'"
}, },
"auth": "'$ZAF_ZBXAPI_AUTH'", "auth": "'$ZAF_ZBXAPI_AUTH'",
"id": 3 "id": 3
}' }'
zaf_zbxapi_do "$impstr" | zaf_zbxapi_getresult | grep -q true zaf_zbxapi_do "$impstr" | zaf_zbxapi_getresult | grep -q true
} }

10
rpm.mk Normal file
View File

@@ -0,0 +1,10 @@
# Makefile for generating rpm packages
# Contrinutions welcome :)
ifeq ($(RPM_PKG),)
RPM_PKG=$(shell . lib/zaf.lib.sh; echo out/zaf-$$ZAF_VERSION.rpm)
endif
$(RPM_PKG):
@echo "Not supported yet. Contributions welcomed! :) "; exit 2

32
tgz.mk Normal file
View File

@@ -0,0 +1,32 @@
TGZ_DIR=tmp/tgz
ifeq ($(TGZ_PKG),)
TGZ_PKG=$(shell . lib/zaf.lib.sh; echo out/zaf-$$ZAF_VERSION.tgz)
endif
$(TGZ_PKG): clean tgz-init tgz-deps tgz-control tgz-scripts tgz-cp tgz-package
tgz-init:
@mkdir -p $(TGZ_DIR)
tgz-deps:
tgz-control:
tgz-scripts:
tgz-cp:
@mkdir -p $(TGZ_DIR)
@set -e; INSTALL_PREFIX=$(TGZ_DIR) ZAF_tgzUG=$(ZAF_tgzUG) ./install.sh auto $(ZAF_OPTIONS) ZAF_PLUGINS="$(ZAF_PLUGINS)" $(AGENT_OPTIONS)
@cat lib/*lib.sh install.sh >$(TGZ_DIR)/usr/lib/zaf/install.sh
@chmod +x $(TGZ_DIR)/usr/lib/zaf/install.sh
@rm -rf $(TGZ_DIR)/tmp
@cp $(TGZ_DIR)/etc/zaf.conf tmp/zaf.conf
@grep -E "$$(echo $(ZAF_EXPORT_OPTS) | tr ' ' '|')=" tmp/zaf.conf >$(TGZ_DIR)/etc/zaf.conf
ifneq ($(AGENT_OPTIONS),)
@echo "ZAF_AGENT_OPTIONS=\"$(AGENT_OPTIONS)\"" >>$(TGZ_DIR)/etc/zaf.conf
endif
tgz-package:
@tar -czf $(TGZ_PKG) -C $(TGZ_DIR) .
@echo PLUGINS embedded: $(ZAF_PLUGINS)
@echo Result: $(TGZ_PKG)

206
zaf
View File

@@ -11,20 +11,28 @@ ZAF_CFG_FILE="/etc/zaf.conf"
# Read options as config for ZAF # Read options as config for ZAF
for pair in "$@"; do for pair in "$@"; do
if echo $pair | grep -qE '^ZAF\_(.*)='; then if echo $pair | grep -qE '^ZAF\_(.*)='; then
option=$(echo $pair|cut -d '=' -f 1) option=$(echo $pair|cut -d '=' -f 1)
value=$(echo $pair|cut -d '=' -f 2-) value=$(echo $pair|cut -d '=' -f 2-)
eval "${option}='$value'" eval "${option}='$value'"
export secondstage=1 export secondstage=1
else else
params="$params $pair" params="$params $pair"
fi fi
done done
export $(set |grep ^ZAF_ | cut -d '=' -f 1) export $(set |grep ^ZAF_ | cut -d '=' -f 1)
# If some variables in cmd were stripped, rerun only with right arguments and exported variables # If some variables in cmd were stripped, rerun only with right arguments and exported variables
[ -n "$secondstage" ] && exec $0 $params [ -n "$secondstage" ] && exec $0 $params
fi fi
export ZAF_BIN=$(realpath $0)
if [ -n "$ZAF_PROXY" ]; then
export ALL_PROXY="$ZAF_PROXY"
export http_proxy="$ZAF_PROXY"
export https_proxy="$ZAF_PROXY"
fi
if [ -f ./lib/zaf.lib.sh ]; then if [ -f ./lib/zaf.lib.sh ]; then
. ./lib/zaf.lib.sh . ./lib/zaf.lib.sh
. ./lib/plugin.lib.sh . ./lib/plugin.lib.sh
@@ -55,6 +63,18 @@ cache-clean)
cache-list) cache-list)
zaf_cache_list zaf_cache_list
;; ;;
cache-test1)
for i in test1 test2 test3; do
echo "To cache:"
echo "$i" | zaf_tocache_stdin "test" 10
done
;;
cache-test2)
for i in test1 test2 test3; do
echo "From cache:"
zaf_fromcache "test"
done
;;
version) version)
echo "$ZAF_VERSION<git $ZAF_GITBRANCH>" echo "$ZAF_VERSION<git $ZAF_GITBRANCH>"
@@ -67,20 +87,33 @@ userparms)
for plugin in $(zaf_list_plugins); do for plugin in $(zaf_list_plugins); do
plugindir=$ZAF_PLUGINS_DIR/$plugin plugindir=$ZAF_PLUGINS_DIR/$plugin
control=$plugindir/control.zaf control=$plugindir/control.zaf
zaf_ctrl_generate_cfg "${control}" "${plugin}" "noscripts" \ zaf_ctrl_generate_items_cfg "${control}" "${plugin}" "noscripts" \
| zaf_far '{PLUGINDIR}' "${plugindir}" | zaf_far '{PLUGINDIR}' "${plugindir}"
done done
;; ;;
agent-config) agent-config)
[ -n "$2" ] && force=yes
for p in $(zaf_list_plugins); do
if [ -f "$ZAF_PLUGINS_DIR/$p/postinst.need" ]; then
zaf_wrn "Calling postinstalation of plugin $p"
zaf_postinstall_plugin $p && rm -f "$ZAF_PLUGINS_DIR/$p/postinst.need"
force=yes
fi
done
zaf_wrn "Generating config files in $ZAF_AGENT_CONFIGD ..." zaf_wrn "Generating config files in $ZAF_AGENT_CONFIGD ..."
for plugin in $(zaf_list_plugins); do for plugin in $(zaf_list_plugins); do
plugindir=$ZAF_PLUGINS_DIR/$plugin plugindir=$ZAF_PLUGINS_DIR/$plugin
control=$plugindir/control.zaf control=$plugindir/control.zaf
zaf_dbg "Generating ${ZAF_AGENT_CONFIGD}/zaf_${plugin}.conf" if ! [ -f "${ZAF_AGENT_CONFIGD}/zaf_${plugin}.conf" ] || [ "$control" -nt "${ZAF_AGENT_CONFIGD}/zaf_${plugin}.conf" ] || [ -n "$force" ]; then
zaf_ctrl_generate_cfg "${control}" "${plugin}" \ zaf_dbg "Generating ${ZAF_AGENT_CONFIGD}/zaf_${plugin}.conf"
| zaf_far '{PLUGINDIR}' "${plugindir}" >${ZAF_AGENT_CONFIGD}/zaf_${plugin}.conf zaf_ctrl_generate_items_cfg "${control}" "${plugin}" \
| zaf_far '{PLUGINDIR}' "${plugindir}" >${ZAF_AGENT_CONFIGD}/zaf_${plugin}.conf
fi
done done
;; ;;
server-config)
zaf_wrn "Not implemented yet"
;;
###### Plugins related commands ###### Plugins related commands
update) update)
@@ -144,9 +177,35 @@ test)
done done
done done
;; ;;
itemsh)
shift
if zaf_is_item "$1"; then
plugin=$(zaf_get_plugin_name "$1")
item=$(zaf_get_item_name "$1")
params=$(zaf_get_item_params "$1")
params2=$(zaf_paramstosh "[$params]")
script=$(zaf_ctrl_generate_items_cfg "${ZAF_PLUGINS_DIR}/${plugin}/control.zaf" "${plugin}" "" "sh -i #"| grep "UserParameter=$plugin.$item" | cut -d ',' -f 2-)
exec sh -c "$script" dummy $params2
else
zaf_err "No such plugin/item $1"
fi
;;
run)
shift
if zaf_is_item "$1"; then
plugin=$(zaf_get_plugin_name "$1")
item=$(zaf_get_item_name "$1")
params=$(zaf_get_item_params "$1")
params2=$(zaf_paramstosh "[$params]")
script=$(zaf_ctrl_generate_items_cfg "${ZAF_PLUGINS_DIR}/${plugin}/control.zaf" "${plugin}" | grep "UserParameter=$plugin.$item" | cut -d ',' -f 2-)
exec sh -c "$script" dummy $params2
else
zaf_err "No such plugin/item $1"
fi
;;
get) get)
shift shift
if echo $1|grep -q '\.'; then if zaf_is_item "$1"; then
zaf_get_item "$1" zaf_get_item "$1"
exit exit
fi fi
@@ -162,6 +221,65 @@ get)
done done
done done
;; ;;
send)
shift
if [ -z "$1" ]; then
# No parameters - pipe to zabbix_sender
zaf_dbg "Waiting for data on stdin (host item value) per line"
zscmd="zabbix_sender -z '$ZAF_ZBXSRV_HOST' -p '$ZAF_ZBXSRV_PORT' -i -"
zaf_dbg $zscmd
eval $zscmd
exit
else
if [ -n "$2" ]; then
# Hostname as parameter - rerun with right hostname set
exec $0 send "$2" "$3" ZAF_HOSTNAME="$1"
else
if echo "$1" | grep -q ':'; then
# Hostname:item - rerun with right hostname set
exec $0 send "$(echo $1 |cut -d ':' -f 2-)" "$3" ZAF_HOSTNAME="$(echo $1 |cut -d ':' -f 1)"
fi
if zaf_is_item "$1"; then
# Item supported by zaf
plugin=$(zaf_get_plugin_name "$1")
item=$(zaf_get_item_name "$1")
zscmd="zabbix_sender -z '$ZAF_ZBXSRV_HOST' -p '$ZAF_ZBXSRV_PORT' -s '$(zaf_hostname)' -k '$plugin.$item' -o '$(zaf_run_item $1)'"
zaf_dbg $zscmd
eval $zscmd
exit
else
if echo $1 | grep -q '='; then
item=$(echo $1 | cut -d '=' -f 1)
value=$(echo $1 | cut -d '=' -f 2-)
else
item=$1
zaf_dbg "Waiting for value of $(zaf_hostname):$1 on stdin"
value=$(cat)
fi
zscmd="zabbix_sender -z '$ZAF_ZBXSRV_HOST' -p '$ZAF_ZBXSRV_PORT' -s '$(zaf_hostname)' -k '$item' -o '$value'"
zaf_dbg $zscmd
eval $zscmd
exit
fi
fi
fi
;;
register)
shift
if [ -z "$1" ]; then
hostname=$(zaf_hostname)
else
hostname="$1"
if [ -z "$2" ]; then
metadata="ZAF"
else
metadata="$2"
fi
fi
zaf_register "$hostname" "$metadata"
exit;
;;
precache) precache)
shift shift
for i in $*; do for i in $*; do
@@ -196,7 +314,12 @@ reinstall)
[ -z "$1" ] && echo "$0 reinstall plugin [plugin]..." [ -z "$1" ] && echo "$0 reinstall plugin [plugin]..."
for p in $@; do for p in $@; do
if zaf_is_plugin "$p"; then if zaf_is_plugin "$p"; then
zaf_remove_plugin "$(basename $p)" params=$(zaf_get_plugin_parameters $p)
for param in $params; do
eval export ZAF_${p}_${param}=$(zaf_get_plugin_parameter "${ZAF_PLUGINS_DIR}/${p}" $param)
zaf_dbg "Saving ZAF_${p}_${param}"
done
zaf_remove_plugin "$p"
reinstalled=1 reinstalled=1
fi fi
zaf_install_plugin "$p" zaf_install_plugin "$p"
@@ -204,7 +327,7 @@ reinstall)
done done
[ -n "$reinstalled" ] && zaf_is_root && zaf_restart_agent [ -n "$reinstalled" ] && zaf_is_root && zaf_restart_agent
;; ;;
remove) remove|uninstall)
shift shift
[ -z "$1" ] && echo "$0 remove plugin [plugin]..." [ -z "$1" ] && echo "$0 remove plugin [plugin]..."
for p in $@; do for p in $@; do
@@ -215,13 +338,28 @@ remove)
done done
[ -n "$removed" ] && zaf_is_root && zaf_restart_agent [ -n "$removed" ] && zaf_is_root && zaf_restart_agent
;; ;;
plugin-set)
plugin="$2"
param="$3"
value="$4"
if [ -z "$plugin" ] || [ -z "$param" ]; then
zaf_err "$0 plugin-set plugin parameter value"
else
if zaf_is_plugin "$plugin"; then
plugindir="${ZAF_PLUGINS_DIR}/${plugin}"
zaf_set_plugin_parameter "$plugindir" "$param" "$value"
else
zaf_err "Plugin $plugin is not installed."
fi
fi
;;
###### Zaf related commands ###### Zaf related commands
self-upgrade) self-upgrade)
shift shift
[ -z "$1" ] && auto=auto [ -z "$1" ] && auto=auto
zaf_os_specific zaf_check_deps zaf && zaf_err "Zaf is installed as system package. Cannot self-upgrade." zaf_os_specific zaf_check_deps zaf && zaf_err "Zaf is installed as system package. Cannot self-upgrade."
if ! which curl >/dev/null; if ! zaf_which curl >/dev/null;
then then
zaf_err "Curl not found. Cannot continue. Please install it." zaf_err "Curl not found. Cannot continue. Please install it."
fi fi
@@ -233,23 +371,24 @@ self-remove)
zaf_os_specific zaf_check_deps zaf && zaf_err "Zaf is installed as system package. Cannot self-remove." zaf_os_specific zaf_check_deps zaf && zaf_err "Zaf is installed as system package. Cannot self-remove."
. /etc/zaf.conf . /etc/zaf.conf
if [ "$1" = "force" ]; then if [ "$1" = "force" ]; then
rm -rf /etc/zaf.conf ${ZAF_PLUGINS_DIR} ${ZAF_REPO_DIR} ${ZAF_LIB_DIR} \ rm -rf /etc/zaf.conf ${ZAF_PLUGINS_DIR} ${ZAF_REPO_DIR} ${ZAF_LIB_DIR} \
${ZAF_BIN_DIR}/zaf ${ZAF_AGENT_CONFIGD}/zaf_* ${ZAF_BIN_DIR}/zaf ${ZAF_AGENT_CONFIGD}/zaf_*
else else
echo "This will remove zaf from this computer and erase all configuration." echo "This will remove zaf from this computer and erase all configuration."
echo "This command will be executed:" echo "This command will be executed:"
echo "rm -rf /etc/zaf.conf ${ZAF_PLUGINS_DIR} ${ZAF_REPO_DIR} ${ZAF_LIB_DIR} \ echo "rm -rf /etc/zaf.conf ${ZAF_PLUGINS_DIR} ${ZAF_REPO_DIR} ${ZAF_LIB_DIR} \
${ZAF_BIN_DIR}/zaf ${ZAF_AGENT_CONFIGD}/zaf_*" ${ZAF_BIN_DIR}/zaf ${ZAF_AGENT_CONFIGD}/zaf_*"
echo echo
echo "To continue, please do $0 self-remove force" echo "To continue, please do $0 self-remove force"
fi fi
;; ;;
###### API related commands ###### API related commands
api) api)
zaf_zbxapi_login zaf_zbxapi_login
case $2 in case $2 in
get-*-id) get-*-id)
obj=$(echo $2|cut -d '-' -f 2) obj=$(echo $2|cut -d '-' -f 2)
[ -z "$3" ] && zaf_err "$0 $1 $2 <$obj>" [ -z "$3" ] && zaf_err "$0 $1 $2 <$obj>"
eval zaf_zbxapi_get${obj}id "$3" eval zaf_zbxapi_get${obj}id "$3"
;; ;;
@@ -400,6 +539,14 @@ api)
;; ;;
*) *)
if zaf_is_plugin "$1"; then
if [ -z "$2" ]; then
zaf_list_plugin_commands "$1"
else
zaf_plugin_run_command "$@"
fi
exit
fi
echo "$0 Version ${ZAF_VERSION}. Please use some of this commands:" echo "$0 Version ${ZAF_VERSION}. Please use some of this commands:"
echo "$0 Cmd [ZAF_OPTION=value] [ZAF_CTRL_Option=value] [ZAF_CTRLI_Item_Option=value] ..." echo "$0 Cmd [ZAF_OPTION=value] [ZAF_CTRL_Option=value] [ZAF_CTRLI_Item_Option=value] ..."
echo "Plugin manipulation commands:" echo "Plugin manipulation commands:"
@@ -416,14 +563,23 @@ api)
echo "Plugin diagnostic commands:" echo "Plugin diagnostic commands:"
zaf_hlp "$0 test [plugin[.item]]" "To test [all] suported items by zabbix_agentd [for plugin]" zaf_hlp "$0 test [plugin[.item]]" "To test [all] suported items by zabbix_agentd [for plugin]"
zaf_hlp "$0 get [plugin[.item]]" "To test [all] suported items by zabbix_get [for plugin]" zaf_hlp "$0 get [plugin[.item]]" "To test [all] suported items by zabbix_get [for plugin]"
zaf_hlp "$0 run [plugin[.item]]" "To test [all] suported items by directly runing command [for plugin]"
zaf_hlp "$0 precache [plugin[.item]]" "To precache [all] suported items" zaf_hlp "$0 precache [plugin[.item]]" "To precache [all] suported items"
zaf_hlp "$0 itemsh plugin.item" "To spawn interactive shell in item context (same as UserParameter)."
echo echo
echo "Zabbix API commands:" echo "Zabbix API commands:"
zaf_hlp "$0 api" "To zabbix API functions. See $0 api for more info." zaf_hlp "$0 api" "To zabbix API functions. See $0 api for more info."
echo echo
echo "Zabbix trapper commands:"
zaf_hlp "$0 send plugin.item" "To send result of agent param directly to Zabbix server by zabbix_server."
zaf_hlp "$0 send item" "To send value for any item from stdin."
zaf_hlp "$0 send host:item" "To send value for any host:item from stdin."
echo "Zabbix agent registration:"
zaf_hlp "$0 register [hostname] [metadata]" "To register hostname on Zabbix server (autoregistration)."
echo
echo "Agent config info commands:" echo "Agent config info commands:"
zaf_hlp "$0 userparms" "See userparms generated from zaf on stdout" zaf_hlp "$0 userparms" "See userparms generated from zaf on stdout"
zaf_hlp "$0 agent-config" "Reconfigure zabbix userparms in $ZAF_AGENT_CONFIGD" zaf_hlp "$0 agent-config [force]" "Reconfigure zabbix userparms in $ZAF_AGENT_CONFIGD"
echo echo
echo "Zaf related commands:" echo "Zaf related commands:"
zaf_hlp "$0 self-upgrade" "To self-upgrade zaf" zaf_hlp "$0 self-upgrade" "To self-upgrade zaf"