diff --git a/extras/chrome_extension/js/background.js b/extras/chrome_extension/js/background.js index 521ecc19eb..037c01a472 100644 --- a/extras/chrome_extension/js/background.js +++ b/extras/chrome_extension/js/background.js @@ -3,309 +3,321 @@ var isFetching = null; var storedEvents = new Array(); var notVisited = {}; -$(window).on('load', function() { - initilise(); - // Wait some ms to throw main function - var delay = setTimeout(main, 100); - resetInterval(); +$(window).on("load", function() { + initilise(); + // Wait some ms to throw main function + var delay = setTimeout(main, 100); + resetInterval(); }); function fetchEvents() { - return storedEvents; + return storedEvents; } function fetchNotVisited() { - return notVisited; + return notVisited; } function removeNotVisited(eventId) { - if (notVisited[eventId] === true) delete notVisited[eventId]; + if (notVisited[eventId] === true) delete notVisited[eventId]; } function main() { + chrome.runtime.sendMessage({ text: "FETCH_EVENTS" }); + // Do not fetch if is fetching now + if (isFetching) return; + isFetching = true; - chrome.runtime.sendMessage({text: "FETCH_EVENTS"}); - // Do not fetch if is fetching now - if (isFetching) return; - isFetching = true; + var url = + localStorage["ip_address"] + + "/include/api.php?op=get&op2=events&return_type=json"; + var feedUrl = url; + var data = new FormData(); - var feedUrl = localStorage["ip_address"]+'/include/api.php?op=get&op2=events&return_type=json&apipass='+localStorage["api_pass"]+'&user='+localStorage["user_name"]+'&pass='+localStorage["pass"]; + data.append("apipass", localStorage["api_pass"]); + data.append("user", localStorage["user_name"]); + data.append("pass", localStorage["pass"]); - req = new XMLHttpRequest(); - req.onload = handleResponse; - req.onerror = handleError; - req.open("GET", feedUrl, true); - req.withCredentials = true - req.send(null); + req = new XMLHttpRequest(); + req.onload = handleResponse; + req.onerror = handleError; + req.open("POST", feedUrl, true); + req.withCredentials = true; + req.send(data); } function handleError() { - chrome.runtime.sendMessage({text: "FETCH_EVENTS_URL_ERROR"}); - isFetching = false; + chrome.runtime.sendMessage({ text: "FETCH_EVENTS_URL_ERROR" }); + isFetching = false; } function handleResponse() { - var doc = req.responseText; - if (doc=="auth error") { - chrome.runtime.sendMessage({text: "FETCH_EVENTS_URL_ERROR"}); - } else { - var n = doc.search("404 Not Found"); - if (n>0) { - chrome.runtime.sendMessage({text: "FETCH_EVENTS_DATA_ERROR"}); - } else { - getEvents(doc); - chrome.runtime.sendMessage({text: "FETCH_EVENTS_SUCCESS"}); - } - } - isFetching = false; + var doc = req.responseText; + if (doc == "auth error") { + chrome.runtime.sendMessage({ text: "FETCH_EVENTS_URL_ERROR" }); + } else { + var n = doc.search("404 Not Found"); + if (n > 0) { + chrome.runtime.sendMessage({ text: "FETCH_EVENTS_DATA_ERROR" }); + } else { + getEvents(doc); + chrome.runtime.sendMessage({ text: "FETCH_EVENTS_SUCCESS" }); + } + } + isFetching = false; } -function getEvents(reply){ - var fetchedEvents = parseReplyEvents(reply); +function getEvents(reply) { + var fetchedEvents = parseReplyEvents(reply); - // If there is no events requested, mark all as visited - if (storedEvents.length == 0) { - notVisited = {}; - storedEvents = fetchedEvents; - return; - } + // If there is no events requested, mark all as visited + if (typeof storedEvents != "undefined" && storedEvents.length == 0) { + notVisited = {}; + storedEvents = fetchedEvents; + return; + } - // Discriminate the new events - newEvents=fetchNewEvents(fetchedEvents,storedEvents); - var newNotVisited = {}; - var notVisitedCount = 0; - - // Check if popup is displayed to make some actions - var views = chrome.extension.getViews({ type: "popup" }); - for(var k=0;k \ +-e DBNAME=pandora \ +-e DBUSER=pandora \ +-e DBPASS=pandora \ +-e DBPORT=3306 \ +-e INSTANCE_NAME=pandora_inst \ +-ti pandorafms/pandorafms-open-stack-el8 +``` + +### Docker Compose Stack + +if you want to run an easy to deploy stack you may use the docker-compose.yml file + +``` +version: '3.1' +services: + db: + image: pandorafms/pandorafms-percona-base + restart: always + #command: ["mysqld", "--innodb-buffer-pool-size=900M"] + environment: + MYSQL_ROOT_PASSWORD: pandora + MYSQL_DATABASE: pandora + MYSQL_USER: pandora + MYSQL_PASSWORD: pandora + networks: + - pandora + + pandora: + image: pandorafms/pandorafms-open-stack-el8:latest + restart: always + depends_on: + - db + environment: + MYSQL_ROOT_PASSWORD: pandora + DBHOST: db + DBNAME: pandora + DBUSER: pandora + DBPASS: pandora + DBPORT: 3306 + INSTANCE_NAME: pandora01 + PUBLICURL: "" + SLEEP: 5 + RETRIES: 10 + networks: + - pandora + ports: + - "8080:80" + - "41121:41121" + - "162:162/udp" + - "9995:9995/udp" +networks: + pandora: +``` +just by running: `docker-compose -f up` + +## Important Parameters: + +* __INSTANCE_NAME__: Pandora Server name +* __DBHOST__: DB host IP to MySQL engine +* __DBNAME__: The name of the database. If your user have enough permissions to create databases, the container will create it in case automatically if didn't exist +* __DBUSER__: The user to connect MySQL engine. +* __DBPASS__: User password to connect MySQL engine. +* __DBPORT__: The port to connect MySQL engine. by default 33306 +* __PUBLICURL__: Define a public URL. Useful when Pandora is used behind a reverse proxy +* __SLEEP__: Time to wait between retries +* __RETRIES__: How many times Pandora will try to connect to MySQL engine before fail. + +Note1: the SLEEP and RETRIES variables will be used to wait for database container to fully start, if you are in a slower system maybe you will need to increase these variables values, in this example will wait 5 seconds for the database container to be up and retries 3 times. + diff --git a/extras/docker/centos8/base/Dockerfile b/extras/docker/centos8/base/Dockerfile new file mode 100644 index 0000000000..285f2f7ef8 --- /dev/null +++ b/extras/docker/centos8/base/Dockerfile @@ -0,0 +1,257 @@ +#docker build -t pandorafms/pandorafms-open-base-el8 -f $HOME/code/pandorafms/extras/docker/centos8/base/Dockerfile $HOME/code/pandorafms/extras/docker/centos8/base/ +#docker push pandorafms/pandorafms-open-base-el8 + +FROM centos:8 + +RUN dnf install -y --setopt=tsflags=nodocs \ + epel-release \ + dnf-utils \ + http://rpms.remirepo.net/enterprise/remi-release-8.rpm + +RUN dnf module reset -y php && dnf module install -y php:remi-7.3 +RUN dnf config-manager --set-enabled PowerTools + +# Install console +RUN dnf install -y --setopt=tsflags=nodocs \ + php \ + php-mcrypt \php-cli \ + php-gd \ + php-curl \ + php-session \ + php-mysqlnd \ + php-ldap \ + php-zip \ + php-zlib \ + php-fileinfo \ + php-gettext \ + php-snmp \ + php-mbstring \ + php-pecl-zip \ + php-xmlrpc \ + libxslt \ + wget \ + php-xml \ + httpd \ + mod_php \ + atk \ + avahi-libs \ + cairo \ + cups-libs \ + fribidi \ + gd \ + gdk-pixbuf2 \ + ghostscript \ + graphite2 \ + graphviz \ + gtk2 \ + harfbuzz \ + hicolor-icon-theme \ + hwdata \ + jasper-libs \ + lcms2 \ + libICE \ + libSM \ + libXaw \ + libXcomposite \ + libXcursor \ + libXdamage \ + libXext \ + libXfixes \ + libXft \ + libXi \ + libXinerama \ + libXmu \ + libXrandr \ + libXrender \ + libXt \ + libXxf86vm \ + libcroco \ + libdrm \ + libfontenc \ + libglvnd \ + libglvnd-egl \ + libglvnd-glx \ + libpciaccess \ + librsvg2 \ + libthai \ + libtool-ltdl \ + libwayland-client \ + libwayland-server \ + libxshmfence \ + mesa-libEGL \ + mesa-libGL \ + mesa-libgbm \ + mesa-libglapi \ + pango \ + pixman \ + nfdump \ + xorg-x11-fonts-75dpi \ + xorg-x11-fonts-misc \ + poppler-data \ + php-yaml; yum clean all + +RUN mkdir -p /run/php-fpm/ ; chown -R root:apache /run/php-fpm/ +# not installed perl-Net-Telnet gtk-update-icon-cach ghostscript-fonts + +# Install server + +RUN dnf install -y --setopt=tsflags=nodocs \ + GeoIP \ + GeoIP-GeoLite-data \ + dwz \ + efi-srpm-macros \ + ghc-srpm-macros \ + go-srpm-macros \ + ocaml-srpm-macros \ + openblas-srpm-macros \ + perl \ + perl-Algorithm-Diff \ + perl-Archive-Tar \ + perl-Archive-Zip \ + perl-Attribute-Handlers \ + perl-B-Debug \ + perl-CPAN \ + perl-CPAN-Meta \ + perl-CPAN-Meta-Requirements \ + perl-CPAN-Meta-YAML \ + perl-Compress-Bzip2 \ + perl-Config-Perl-V \ + perl-DBD-MySQL \ + perl-DBI \ + perl-DB_File \ + perl-Data-Dump \ + perl-Data-OptList \ + perl-Data-Section \ + perl-Devel-PPPort \ + perl-Devel-Peek \ + perl-Devel-SelfStubber \ + perl-Devel-Size \ + perl-Digest-HMAC \ + perl-Digest-SHA \ + perl-Encode-Locale \ + perl-Encode-devel \ + perl-Env \ + perl-ExtUtils-CBuilder \ + perl-ExtUtils-Command \ + perl-ExtUtils-Embed \ + perl-ExtUtils-Install \ + perl-ExtUtils-MM-Utils \ + perl-ExtUtils-MakeMaker \ + perl-ExtUtils-Manifest \ + perl-ExtUtils-Miniperl \ + perl-ExtUtils-ParseXS \ + perl-File-Fetch \ + perl-File-HomeDir \ + perl-File-Listing \ + perl-File-Which \ + perl-Filter \ + perl-Filter-Simple \ + perl-Geo-IP \ + perl-HTML-Parser \ + perl-HTML-Tagset \ + perl-HTML-Tree \ + perl-HTTP-Cookies \ + perl-HTTP-Date \ + perl-HTTP-Message \ + perl-HTTP-Negotiate \ + perl-IO-HTML \ + perl-IO-Socket-INET6 \ + perl-IO-Zlib \ + perl-IO-stringy \ + perl-IPC-Cmd \ + perl-IPC-SysV \ + perl-IPC-System-Simple \ + perl-JSON \ + perl-JSON-PP \ + perl-LWP-MediaTypes \ + perl-Locale-Codes \ + perl-Locale-Maketext \ + perl-Locale-Maketext-Simple \ + perl-MRO-Compat \ + perl-Math-BigInt \ + perl-Math-BigInt-FastCalc \ + perl-Math-BigRat \ + perl-Memoize \ + perl-Module-Build \ + perl-Module-CoreList \ + perl-Module-CoreList-tools \ + perl-Module-Load \ + perl-Module-Load-Conditional \ + perl-Module-Loaded \ + perl-Module-Metadata \ + perl-NTLM \ + perl-Net-HTTP \ + perl-Net-Ping \ + perl-NetAddr-IP \ + perl-Package-Generator \ + perl-Params-Check \ + perl-Params-Util \ + perl-Perl-OSType \ + perl-PerlIO-via-QuotedPrint \ + perl-Pod-Checker \ + perl-Pod-Html \ + perl-Pod-Parser \ + perl-SelfLoader \ + perl-Socket6 \ + perl-Software-License \ + perl-Sub-Exporter \ + perl-Sub-Install \ + perl-Sys-Syslog \ + perl-Test \ + perl-Test-Harness \ + perl-Test-Simple \ + perl-Text-Balanced \ + perl-Text-Diff \ + perl-Text-Glob \ + perl-Text-Template \ + perl-Thread-Queue \ + perl-Time-Piece \ + perl-TimeDate \ + perl-Try-Tiny \ + perl-Unicode-Collate \ + perl-WWW-RobotRules \ + perl-XML-NamespaceSupport \ + perl-XML-Parser \ + perl-XML-SAX \ + perl-XML-SAX-Base \ + perl-XML-Simple \ + perl-XML-Twig \ + perl-autodie \ + perl-bignum \ + perl-devel \ + perl-encoding \ + perl-experimental \ + perl-inc-latest \ + perl-libnetcfg \ + perl-libwww-perl \ + perl-local-lib \ + perl-open \ + perl-perlfaq \ + perl-srpm-macros \ + perl-utils \ + perl-version \ + python-srpm-macros \ + python3-pyparsing \ + python3-rpm-macros \ + qt5-srpm-macros \ + redhat-rpm-config \ + rust-srpm-macros \ + systemtap-sdt-devel \ + perl-TermReadKey \ + perl \ + perl-DBD-MySQL \ + perl-DBI \ + initscripts \ + net-tools \ + nmap-ncat \ + nmap \ + net-snmp-utils \ + sudo \ + http://firefly.artica.es/centos8/perl-Net-Telnet-3.04-1.el8.noarch.rpm \ + http://www6.atomicorp.com/channels/atomic/centos/7/x86_64/RPMS/wmi-1.3.14-4.el7.art.x86_64.rpm + + +RUN dnf install -y supervisor crontabs mysql http://firefly.artica.es/centos8/phantomjs-2.1.1-1.el7.x86_64.rpm --setopt=tsflags=nodocs + + +EXPOSE 80 443 41121 162/udp diff --git a/extras/docker/centos8/build_image_el8.sh b/extras/docker/centos8/build_image_el8.sh new file mode 100755 index 0000000000..00c50f6ff2 --- /dev/null +++ b/extras/docker/centos8/build_image_el8.sh @@ -0,0 +1,112 @@ +#!/bin/bash + +VERSION=$1 +ENT="$HOME/code/pandora_enterprise" +OPEN="$HOME/code/pandorafms" +OS="Centos" +ARCH="x86_64" +EL="el7" +EXT="demo" +TARGET_URL="http://atlantis.artica.es" +DOCKER_PATH="$OPEN/extras/docker/centos8/" +OSTACK_IMAGE="pandorafms/pandorafms-open-stack-el8" +OBASE_IMAGE="pandorafms/pandorafms-open-base-el8" +PERCONA_IMAGE="pandorafms/pandorafms-percona-base" + + +function help { + echo "To excute the builder you must declare 4 parameters: the version image, upload (push) tokens, build base (rebuild centos base image), build percona (rebuild percona base image)" + echo "" + echo "$0 [ ] [] []" + echo "Ex creates a local image from 749 packages : $0 749 0 1 1" +} + +if [ "$1" == "" ] || [ "$1" == "-h" ] ; then + help + exit +fi + +if [ "$2" == "1" ]; then + UPDATE="1" +fi + +if [ "$3" == "1" ]; then + BASEBUILD="1" +fi + +if [ "$4" == "1" ]; then + DBBUILD="1" +fi + +#Defining packages urls + +oconsoleurl=$TARGET_URL/Releases/7.0NG.$VERSION/$OS/noarch/pandorafms_console-7.0NG.$VERSION.noarch.rpm +oserverurl=$TARGET_URL/Releases/7.0NG.$VERSION/$OS/noarch/pandorafms_server-7.0NG.$VERSION.noarch.rpm +url=$(curl -I -s $TARGET_URL/Releases/7.0NG.$VERSION/ 2> /dev/null | grep "200 OK" | wc -l) + +# log in into docker acount to acces private repo. + +# docker login -u $DOCKERUSER -p$DOCKERPASS + +Check athlantis is reachable +if [ "$url" -lt 1 ] ; then + echo "$url Athlantis unreachable ..." + exit +fi + +echo "Start" +# Removing old packages +cd $DOCKER_PATH/pandora-stack/sources +rm -rf ./pandorafms_* + +# Downloading new packages +wget $oconsoleurl +wget $oserverurl + +if [ "$BASEBUILD" == 1 ] ; then + # Open Base image + echo "building Base el8 image" + cd $DOCKER_PATH/base + docker build -t $OBASE_IMAGE:$VERSION -f $DOCKER_PATH/base/Dockerfile $DOCKER_PATH/base + echo "Taging Open stack el8 latest image before upload" + docker tag $OBASE_IMAGE:$VERSION $OBASE_IMAGE:latest + echo -e ">>>> \n" +fi + +if [ "$DBBUILD" == 1 ] ; then + # Percona image + echo "building Percona image" + cd $OPEN/extras/docker/percona + docker build -t $PERCONA_IMAGE:latest -f $OPEN/extras/docker/percona/Dockerfile $OPEN/extras/docker/percona + echo -e ">>>> \n" +fi + +#Open Stack image +echo "building Open el8 image" +cd $DOCKER_PATH/pandora-stack +docker build -t $OSTACK_IMAGE:$VERSION -f $DOCKER_PATH/pandora-stack/Dockerfile $DOCKER_PATH/pandora-stack +echo "Taging Open base latest image before upload" +docker tag $OSTACK_IMAGE:$VERSION $OSTACK_IMAGE:latest +echo -e ">>>> \n" + +# Upload images + +if [ "$UPDATE" == 1 ] ; then + if [ "$BASEBUILD" == 1 ] ; then + #Open base Images + echo "Uploading Open $OBASE_IMAGE:$VERSION . . ." + docker push $OBASE_IMAGE:$VERSION + docker push $OBASE_IMAGE:latest + fi + + if [ "$DBBUILD" == 1 ] ; then + #Open base Images + echo "Uploading percona $PERCONA_IMAGE:latest . . ." + docker push $PERCONA_IMAGE:latest + fi + + #Open Stack Images + echo "Uploading Open $OSTACK_IMAGE:$VERSION . . ." + docker push $OSTACK_IMAGE:$VERSION + docker push $OSTACK_IMAGE:latest +fi diff --git a/extras/docker/centos8/docker-compose.yml b/extras/docker/centos8/docker-compose.yml new file mode 100644 index 0000000000..5ac5385133 --- /dev/null +++ b/extras/docker/centos8/docker-compose.yml @@ -0,0 +1,43 @@ +# Use root/example as user/password credentials +# este compose incluye la base de datos en otro docker y levanta aplicacion y DB juntos +version: '3.1' + +services: + + db: + image: pandorafms/pandorafms-percona-base + restart: always + #command: ["mysqld", "--innodb-buffer-pool-size=900M"] + environment: + MYSQL_ROOT_PASSWORD: pandora + MYSQL_DATABASE: pandora + MYSQL_USER: pandora + MYSQL_PASSWORD: pandora + networks: + - pandora + + pandora: + image: pandorafms/pandorafms-open-stack-el8:latest + restart: always + depends_on: + - db + environment: + MYSQL_ROOT_PASSWORD: pandora + DBHOST: db + DBNAME: pandora + DBUSER: pandora + DBPASS: pandora + DBPORT: 3306 + INSTANCE_NAME: pandora01 + PUBLICURL: "" + SLEEP: 5 + RETRIES: 10 + networks: + - pandora + ports: + - "8080:80" + - "41121:41121" + - "162:162/udp" + - "9995:9995/udp" +networks: + pandora: diff --git a/extras/docker/centos8/pandora-stack/Dockerfile b/extras/docker/centos8/pandora-stack/Dockerfile new file mode 100644 index 0000000000..59728b37d6 --- /dev/null +++ b/extras/docker/centos8/pandora-stack/Dockerfile @@ -0,0 +1,24 @@ +#docker build -t pandorafms/pandorafms-open-stack-el8:$VERSION -f $HOME/code/pandorafms/extras/docker/centos8/pandora-stack/Dockerfile $HOME/code/pandorafms/extras/docker/centos8/pandora-stack/ + +FROM pandorafms/pandorafms-open-base-el8 + +ENV DBNAME=pandora +ENV DBUSER=pandora +ENV DBPASS=pandora +ENV DBHOST=pandora +ENV DBPORT=3306 +ENV SLEEP=5 +ENV RETRIES=1 +ENV OPEN=1 + +ENV LC_ALL=C + +RUN rm -rf /etc/localtime ; ln -s /usr/share/zoneinfo/Europe/Madrid /etc/localtime + +COPY ./sources /opt/pandora +# Install the Pandora console +RUN dnf install -y /opt/pandora/pandorafms_console-*.rpm /opt/pandora/pandorafms_server-*.rpm ; yum clean all + +EXPOSE 80 443 41121 162/udp 9995/udp + +CMD sh /opt/pandora/init_pandora.sh diff --git a/extras/docker/centos8/pandora-stack/sources/.gitignore b/extras/docker/centos8/pandora-stack/sources/.gitignore new file mode 100644 index 0000000000..9e870cb2e3 --- /dev/null +++ b/extras/docker/centos8/pandora-stack/sources/.gitignore @@ -0,0 +1,5 @@ +# exclude packages +demos/ +*.tar* +*.rpm +phantomjs diff --git a/extras/docker/centos8/pandora-stack/sources/init_pandora.sh b/extras/docker/centos8/pandora-stack/sources/init_pandora.sh new file mode 100755 index 0000000000..56424e6cb9 --- /dev/null +++ b/extras/docker/centos8/pandora-stack/sources/init_pandora.sh @@ -0,0 +1,336 @@ +#!/bin/bash +# +# Prepares environment and launchs Pandora FMS +# +# Global vars +# +PANDORA_CONSOLE=/var/www/html/pandora_console +PANDORA_SERVER_CONF=/etc/pandora/pandora_server.conf +PANDORA_SERVER_BIN=/usr/bin/pandora_server +PANDORA_HA_BIN=/usr/bin/pandora_ha +PANDORA_TABLES_MIN=160 +# +# Check database +# +function db_check { + # Check DB + echo -n ">> Checking dbengine connection: " + + for i in `seq $RETRIES`; do + r=`echo 'select 1' | mysql -u$DBUSER -p$DBPASS -P$DBPORT -h$DBHOST -A` + if [ $? -ne 0 ]; then + echo -n "retriying DB conection in $SLEEP seconds: " + sleep $SLEEP + else + break + fi + done + + r=`echo 'select 1' | mysql -u$DBUSER -p$DBPASS -P$DBPORT -h$DBHOST -A` + if [ $? -eq 0 ]; then + echo "OK" + echo -n ">> Checking database connection: " + r=`echo 'select 1' | mysql -u$DBUSER -p$DBPASS -P$DBPORT -h$DBHOST -A $DBNAME` + if [ $? -eq 0 ]; then + echo "OK" + return 0 + fi + echo -n ">> Cannot connect to $DBNAME, trying to create: " + r=`echo "create database $DBNAME" | mysql -u$DBUSER -p$DBPASS -P$DBPORT -h$DBHOST` + if [ $? -eq 0 ]; then + echo "OK" + return 0 + fi + echo "Cannot create database $DBNAME on $DBUSER@$DBHOST:$DBPORT" + + return 1 + fi + + if [ "$DEBUG" == "1" ]; then + echo "Command: [echo 'select 1' | mysql -u$DBUSER -p$DBPASS -P$DBPORT -h$DBHOST -A $DBNAME]" + echo "Output: [$r]" + + traceroute $DBHOST + nmap $DBHOST -v -v -p $DBPORT + fi + + + return 1 +} + +# Load database +# +function db_load { + # Load DB + echo -n ">> Checking database state:" + r=`mysql -u$DBUSER -p$DBPASS -P$DBPORT -h$DBHOST -A $DBNAME -s -e 'show tables'| wc -l` + if [ "$DEBUG" == "1" ]; then + echo "Command: [mysql -u$DBUSER -p$DBPASS -P$DBPORT -h$DBHOST -A $DBNAME -s -e 'show tables'| wc -l]" + echo "Output: [$r]" + fi + + if [ "$r" -ge "$PANDORA_TABLES_MIN" ]; then + echo 'OK. Already exists, '$r' tables detected' + return 0 + fi + echo 'Empty database detected'; + + # Needs to be loaded. + echo -n "- Loading database schema: " + r=`mysql -u$DBUSER -p$DBPASS -P$DBPORT -h$DBHOST $DBNAME < $PANDORA_CONSOLE/pandoradb.sql` + if [ $? -ne 0 ]; then + echo "mysql -u$DBUSER -p$DBPASS -P$DBPORT -h$DBHOST $DBNAME < $PANDORA_CONSOLE/pandoradb.sql" + echo "ERROR" + echo "$r" + return 1; + fi + echo "OK" + + echo -n "- Loading database data: " + r=`mysql -u$DBUSER -p$DBPASS -P$DBPORT -h$DBHOST $DBNAME < $PANDORA_CONSOLE/pandoradb_data.sql` + if [ $? -ne 0 ]; then + echo "ERROR" + echo $r + return 2; + fi + echo "OK" + + # Loaded. + return 0 +} + +# +# Prepare & start Pandora FMS Console +# +function console_prepare { + CONSOLE_PATH=/var/www/html/pandora_console + + echo ">> Preparing console" + # Delete install and license files. + mv $CONSOLE_PATH/install.php $CONSOLE_PATH/install.done + rm -f $CONSOLE_PATH/enterprise/PandoraFMS_Enteprise_Licence.txt + + # Configure console. + cat > $CONSOLE_PATH/include/config.php << EO_CONFIG_F + /etc/httpd/conf.d/pandora.conf << EO_CONFIG_F + + Options Indexes FollowSymLinks + AllowOverride All + Require all granted + + +EO_CONFIG_F + + cat > /var/www/html/index.html << EOF_INDEX + +EOF_INDEX + + echo "- Fixing permissions" + chmod 600 $CONSOLE_PATH/include/config.php + chown -R apache. $CONSOLE_PATH + + # prepare php.ini + sed -i -e "s/^max_input_time.*/max_input_time = -1/g" /etc/php.ini + sed -i -e "s/^max_execution_time.*/max_execution_time = 0/g" /etc/php.ini + sed -i -e "s/^upload_max_filesize.*/upload_max_filesize = 800M/g" /etc/php.ini + sed -i -e "s/^memory_limit.*/memory_limit = 500M/g" /etc/php.ini + + echo "- Setting Public URL: $PUBLICURL" + q=$(mysql -u$DBUSER -p$DBPASS $DBNAME -h$DBHOST -sNe "select token from tconfig;" | grep public_url) + [[ ! "$q" ]] && mysql -u $DBUSER -p$DBPASS $DBNAME -P$DBPORT -h$DBHOST -sNe "INSERT INTO tconfig (token,value) VALUES ('public_url',\"$PUBLICURL\");" + mysql -u$DBUSER -p$DBPASS $DBNAME -h$DBHOST -sNe "UPDATE tconfig SET value=\"$PUBLICURL\" WHERE token=\"public_url\";" + +#touch $CONSOLE_PATH/pandora_console.log +#chown apache. $CONSOLE_PATH/pandora_console.log + +} + +function check_mr { + ## geting MR + Package + CMR=$(mysql -u$DBUSER -p$DBPASS $DBNAME -h$DBHOST -sNe "select value from tconfig where token = 'MR'") + CPK=$(mysql -u$DBUSER -p$DBPASS $DBNAME -h$DBHOST -sNe "select value from tconfig where token = 'current_package_enterprise'") + + DPK=$(grep pandora_version $PANDORA_CONSOLE/include/config_process.php | awk '{print $3}' | tr -d "'" | tr -d ";" | cut -d . -f 3) + DMR=$(ls $PANDORA_CONSOLE/extras/mr/ | sort -n | tail -1 | cut -d . -f 1) + + if [[ $DMR -gt $CMR ]]; then + echo ">> Fixing DB: MR: $CMR Current Package: $CPK Desired MR: $DMR" + cd $PANDORA_CONSOLE/extras/mr/ + for i in $(ls | sort -n); do + cat $i | mysql -u$DBUSER -p$DBPASS $DBNAME -h$DBHOST + done + cd - + + echo ">> Updating DB: MR: $CMR Current Package: $CPK Desired MR: $DMR" + + mysql -u $DBUSER -p$DBPASS $DBNAME -h$DBHOST -sNe "update tconfig set value = $DMR where token = 'MR';" + mysql -u $DBUSER -p$DBPASS $DBNAME -h$DBHOST -sNe "update tconfig set value = $DPK where token = 'current_package_enterprise';" + fi + + +} + +function server_prepare { + sed -i -e "s/^dbhost.*/dbhost $DBHOST/g" $PANDORA_SERVER_CONF + sed -i -e "s/^dbname.*/dbname $DBNAME/g" $PANDORA_SERVER_CONF + sed -i -e "s/^dbuser.*/dbuser $DBUSER/g" $PANDORA_SERVER_CONF + sed -i -e "s|^dbpass.*|dbpass $DBPASS|g" $PANDORA_SERVER_CONF + sed -i -e "s/^dbport.*/dbport $DBPORT/g" $PANDORA_SERVER_CONF + sed -i -e "s/^#servername.*/servername $INSTANCE_NAME/g" $PANDORA_SERVER_CONF + echo "pandora_service_cmd /etc/init.d/pandora_server" >> $PANDORA_SERVER_CONF + + # prepare snmptrapd + cat > /etc/snmp/snmptrapd.conf << EOF +authCommunity log public +disableAuthorization yes +EOF + + ## Enable WUX + if [ "$WUX_SERVER" == "1" ] && [ "$WUX_HOST" ]; then + if [ ! $WUX_PORT ]; then + WUX_PORT=4444 + fi + echo "Enabling WUX server HOST=$WUX_HOST PORT=$WUX_PORT" + sed -i -r "s/#?wuxserver.*/wuxserver 1/g" $PANDORA_SERVER_CONF + sed -i -r "s/#?wux_host.*/wux_host $WUX_HOST/g" $PANDORA_SERVER_CONF + sed -i -r "s/#?wux_port.*/wux_port $WUX_PORT/g" $PANDORA_SERVER_CONF + + fi +} + + +## +## MAIN +## + +if [ "$DBUSER" == "" ] || [ "$DBPASS" == "" ] || [ "$DBNAME" == "" ] || [ "$DBHOST" == "" ]; then + echo "Required environemntal variables DBUSER, DBPASS, DBNAME, DBHOST" + exit 1 +fi +if [ "$DBPORT" == "" ]; then + DBPORT=3306 +fi + +echo "" > /opt/pandora/crontasks || touch /opt/pandora/crontasks + + +#install pandora packages +echo "-> Istalling pandorafms" +cd /opt/pandora +useradd pandora + +if [[ $OPEN != 1 ]]; then + # install enterprise + dnf install -y /opt/pandora/pandorafms_console*.rpm + tar xvfz /opt/pandora/pandorafms_server_*tar* && cd pandora_server && ./pandora_server_installer --install ; rm -rf /opt/pandora/pandora_server + [[ -e /var/www/html/pandora_console/include/config.php ]] || yum reinstall -y /opt/pandora/pandorafms*.rpm + PANDORA_BIN="pandora_ha" + PANDORA_EXEC="/usr/bin/pandora_ha /etc/pandora/pandora_server.conf" +else + install only open + dnf install -y /opt/pandora/pandorafms_console-*.rpm /opt/pandora/pandorafms_server-*.rpm + dnf reinstall -y /opt/pandora/pandorafms_server-*.rpm + [[ -e /var/www/html/pandora_console/include/config.php ]] || dnf reinstall -y /opt/pandora/pandorafms_console-*.rpm + PANDORA_BIN="pandora_server" + PANDORA_EXEC="/usr/bin/pandora_server /etc/pandora/pandora_server.conf" +fi + + + +db_check && db_load + +# Sync to MC. +if [ "$META_DBNAME" != "" ] && [ "$META_DBHOST" != "" ]; then + if [ "$META_DBPORT" == "" ]; then + META_DBPORT=3306 + fi + register_mc +fi + +check_mr +console_prepare +server_prepare + +echo ">> Enable oracle env file cron: " +cat > /etc/pandora/pandora_server.env << 'EOF_ENV' +#!/bin/bash +VERSION=19.8 +export PATH=$PATH:$HOME/bin:/usr/lib/oracle/$VERSION/client64/bin +export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/lib/oracle/$VERSION/client64/lib +export ORACLE_HOME=/usr/lib/oracle/$VERSION/client64 +EOF_ENV + +echo ">> Enable discovery cron: " +#while true ; do wget -q -O - --no-check-certificate http://localhost/pandora_console/enterprise/cron.php >> /var/www/html/pandora_console/pandora_console.log && sleep 60 ; done & +echo "*/5 * * * * wget -q -O - --no-check-certificate http://localhost/pandora_console/enterprise/cron.php >> /var/www/html/pandora_console/log/cron.log" >> /opt/pandora/crontasks + +echo ">> Enable pandora_db cron: " +/usr/bin/perl /usr/share/pandora_server/util/pandora_db.pl /etc/pandora/pandora_server.conf +#while true ; do sleep 1h && /usr/bin/pandora_db /etc/pandora/pandora_server.conf; done & +echo "0 */1 * * * /usr/bin/pandora_db /etc/pandora/pandora_server.conf" >> /opt/pandora/crontasks + +echo ">> Loading crontab tasks" +crontab -r +crontab /opt/pandora/crontasks && crontab -l + +ip addr | grep -w "inet" | grep -v "127.0.0.1" | grep -v -e "172.1[0-9].0.1" | awk '{print $2}' | awk -F '/' '{print "-> Go to http://"$1"/pandora_console to manage this server"}' + +# Check and launch supervisord +echo ">> Starting process: Running supervisord" +# Create supervisor.conf + +cat > /etc/supervisord.conf << EOF_CON +[unix_http_server] +file=/tmp/supervisor.sock + +[supervisord] +nodaemon=true +loglevel = debug + +[program:php-fpm] +command=/usr/sbin/php-fpm -F +riredirect_stderr=true + +[program:httpd] +command=/usr/sbin/apachectl -DFOREGROUND +riredirect_stderr=true + +[program:tentacle] +command=/etc/init.d/tentacle_serverd restart + +[program:$PANDORA_BIN] +command=$PANDORA_EXEC +riredirect_stderr=true + +[program:cron] +command=crond -n + +[group:allservices] +programs=httpd,cron,php-fpm,$PANDORA_BIN,tentacle + +[rpcinterface:supervisor] +supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface + +[supervisorctl] +serverurl=unix:///tmp/supervisor.sock + +EOF_CON + +# execute supervisor +touch /var/log/pandora/pandora_server.log ; tail -F /var/log/pandora/* & +su - -c supervisord diff --git a/extras/docker/percona/Dockerfile b/extras/docker/percona/Dockerfile new file mode 100644 index 0000000000..82b97401d6 --- /dev/null +++ b/extras/docker/percona/Dockerfile @@ -0,0 +1,31 @@ + +#docker build -t pandorafms/pandorafms-percona-base -f $HOME/code/pandorafms/extras/docker/percona/Dockerfile $HOME/code/pandorafms/extras/docker/percona + +FROM percona:5.7 + +RUN echo -e '#PandoraFMS configuration \n\ +[mysqld] \n\ +max_allowed_packet = 64M \n\ +innodb_buffer_pool_size = 500M \n\ +innodb_lock_wait_timeout = 90 \n\ +innodb_file_per_table \n\ +innodb_flush_log_at_trx_commit = 0 \n\ +innodb_flush_method = O_DIRECT \n\ +innodb_log_file_size = 64M \n\ +innodb_log_buffer_size = 16M \n\ +innodb_io_capacity = 100 \n\ +thread_cache_size = 8 \n\ +thread_stack = 256K \n\ +max_connections = 100 \n \n\ +key_buffer_size=4M \n\ +read_buffer_size=128K \n\ +read_rnd_buffer_size=128K \n\ +sort_buffer_size=128K \n\ +join_buffer_size=4M \n\n\ +query_cache_type = 1 \n\ +query_cache_size = 64M \n\ +query_cache_min_res_unit = 2k \n\ +query_cache_limit = 256K \n\n\ +sql_mode="" ' > /etc/my.cnf.d/pandora.cnf + +EXPOSE 3306 diff --git a/extras/docker/percona/README.MD b/extras/docker/percona/README.MD new file mode 100644 index 0000000000..036cf7e0f9 --- /dev/null +++ b/extras/docker/percona/README.MD @@ -0,0 +1,50 @@ +![Image of Pandora FMS](https://pandorafms.org/wp-content/uploads/2016/06/logo_pandora_community.png) + +# Pandora FMS database container + +This container image is designed for optimal performance using Pandora FMS. + +Is based on the official Percona database image turned to get the maximum performance on PandoraFMS + +## Official Gitgub repo + +Dockerfiles and more info in our official repository: https://github.com/pandorafms/pandorafms/tree/develop/extras/docker/percona + +## USAGE + +Similar to the official percona image: +Example: +``` +docker run --name Pandora_DB \ +-p 3306:3306 \ +-e MYSQL_ROOT_PASSWORD=pandora \ +-e MYSQL_DATABASE=pandora \ +-e MYSQL_USER=pandora \ +-e MYSQL_PASSWORD=pandora \ +-d pandorafms/pandorafms-percona-base +``` + +## Environment Variables +When you start the percona image, you can adjust the configuration of the instance by passing one or more environment variables on the docker run command line. Do note that none of the variables below will have any effect if you start the container with a data directory that already contains a database: any pre-existing database will always be left untouched on container startup. + +__MYSQL_ROOT_PASSWORD__ : This variable is mandatory and specifies the password that will be set for the root superuser account. In the above example, it was set to my-secret-pw. + +__MYSQL_ROOT_HOST__ : By default, root can connect from anywhere. This option restricts root connections to be from the specified host only. Also localhost can be used here for the local-only root access. + +__MYSQL_DATABASE__ : +This variable is optional and allows you to specify the name of a database to be created on image startup. If a user/password was supplied (see below) then that user will be granted superuser access (corresponding to GRANT ALL) to this database. + +__MYSQL_USER, MYSQL_PASSWORD__ :These variables are optional, used in conjunction to create a new user and to set that user's password. This user will be granted superuser permissions (see above) for the database specified by the MYSQL_DATABASE variable. Both variables are required for a user to be created. +Do note that there is no need to use this mechanism to create the root superuser, that user gets created by default with the password specified by the MYSQL_ROOT_PASSWORD variable. + +__MYSQL_ALLOW_EMPTY_PASSWORD__ : This is an optional variable. Set to yes to allow the container to be started with a blank password for the root user. NOTE: Setting this variable to yes is not recommended unless you really know what you are doing, since this will leave your instance completely unprotected, allowing anyone to gain complete superuser access. + +__MYSQL_RANDOM_ROOT_PASSWORD__ : This is an optional variable. Set to yes to generate a random initial password for the root user (using pwgen). The generated root password will be printed to stdout (GENERATED ROOT PASSWORD: .....). + +__MYSQL_ONETIME_PASSWORD__ : Sets root (not the user specified in MYSQL_USER!) user as expired once init is complete, forcing a password change on first login. NOTE: This feature is supported on MySQL 5.6+ only. Using this option on MySQL 5.5 will throw an appropriate error during initialization. + +__MYSQL_INITDB_SKIP_TZINFO__ : At first run MySQL automatically loads from the local system the timezone information needed for the CONVERT_TZ() function. If it's is not what is intended, this option disables timezone loading. + +__INIT_TOKUDB__ : Tuns on TokuDB Engine. It can be activated only when transparent huge pages (THP) are disabled. + +__INIT_ROCKSDB__ : Tuns on RocksDB Engine. \ No newline at end of file diff --git a/extras/firefox_extension/chrome/content/js/main.js b/extras/firefox_extension/chrome/content/js/main.js index a5452c5bf4..c9cd394197 100644 --- a/extras/firefox_extension/chrome/content/js/main.js +++ b/extras/firefox_extension/chrome/content/js/main.js @@ -1,245 +1,262 @@ -if ("undefined" == typeof(PandoraChrome)) { - var PandoraChrome = {}; - var prefManager = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService).getBranch("pandora."); +/* globals Components, req */ +if ("undefined" == typeof PandoraChrome) { + var PandoraChrome = {}; + var prefManager = Components.classes["@mozilla.org/preferences-service;1"] + .getService(Components.interfaces.nsIPrefService) + .getBranch("pandora."); - var timer = null; - var allEvents=new Array(); - var newEvents=new Array(); - var oldEvents=new Array(); - var api_div_numbers=21; -}; - - - - - -PandoraChrome.fn = function(){ - return { - displaySideBar: function(){ - PandoraChrome.fn.hideNotification(); - PandoraChrome.fn.hideBadge(); - toggleSidebar('viewPandoraSidebar'); - }, - displayDialog : function(){ - window.openDialog("chrome://pandorasidebar/content/options.xul", "","chrome, centerscreen, dialog, modal, resizable=no", null).focus(); - }, - handleClick: function(e){ - if(e.button == 0){ - toggleSidebar('viewPandoraSidebar'); - PandoraChrome.fn.setIcon('icon16'); - } - }, - - Onloading: function () { - if(prefManager.getBoolPref("firstLoad")){ - prefManager.setIntPref("new_events",prefManager.getIntPref("events")); - prefManager.setBoolPref("firstLoad",false); - } + var timer = null; + var allEvents = new Array(); + var newEvents = new Array(); + var oldEvents = new Array(); + var api_div_numbers = 21; +} - if(timer) { - clearTimeout(timer); - } - timer =setTimeout(PandoraChrome.fn.main , 100 ); - }, +PandoraChrome.fn = (function() { + return { + displaySideBar: function() { + PandoraChrome.fn.hideNotification(); + PandoraChrome.fn.hideBadge(); + toggleSidebar("viewPandoraSidebar"); + }, + displayDialog: function() { + window + .openDialog( + "chrome://pandorasidebar/content/options.xul", + "", + "chrome, centerscreen, dialog, modal, resizable=no", + null + ) + .focus(); + }, + handleClick: function(e) { + if (e.button == 0) { + toggleSidebar("viewPandoraSidebar"); + PandoraChrome.fn.setIcon("icon16"); + } + }, - + Onloading: function() { + if (prefManager.getBoolPref("firstLoad")) { + prefManager.setIntPref("new_events", prefManager.getIntPref("events")); + prefManager.setBoolPref("firstLoad", false); + } - main: function() { - // alert('test_main'); - var url=prefManager.getCharPref("ip_address")+'/include/api.php?op=get&op2=events&return_type=csv&apipass='+prefManager.getCharPref("api_pass")+'&user='+prefManager.getCharPref("user_name")+'&pass='+prefManager.getCharPref("pass"); - var feedUrl = url; - prefManager.setBoolPref("data_check", true); - req = new XMLHttpRequest(); - req.onload = PandoraChrome.fn.handleResponse; - req.onerror = PandoraChrome.fn.handleError; - req.open("GET", feedUrl, true); - req.send(null); - }, + if (timer) { + clearTimeout(timer); + } + timer = setTimeout(PandoraChrome.fn.main, 100); + }, - handleError: function() { - //alert("error"); - prefManager.setCharPref("data",null); - prefManager.setBoolPref("data_check", false); - if(timer) { - clearTimeout(timer); - } - timer =setTimeout(PandoraChrome.fn.main , 1000); - }, + main: function() { + // alert('test_main'); + var url = + prefManager.getCharPref("ip_address") + + "/include/api.php?op=get&op2=events&return_type=json"; + var feedUrl = url; + var data = new FormData(); - handleResponse: function () { - var doc = req.responseText; - if (doc=="auth error") { - prefManager.setCharPref("data",null); - prefManager.setBoolPref("data_check", false); - if(timer) { - clearTimeout(timer); - } - timer =setTimeout(PandoraChrome.fn.main , 1000); + data.append("apipass", prefManager.getCharPref("api_pass")); + data.append("user", prefManager.getCharPref("user_name")); + data.append("pass", prefManager.getCharPref("pass")); - } - else{ - var n=doc.search("404 Not Found"); - if(n>0){ + prefManager.setBoolPref("data_check", true); + req = new XMLHttpRequest(); + req.onload = PandoraChrome.fn.handleResponse; + req.onerror = PandoraChrome.fn.handleError; + req.open("POST", feedUrl, true); + req.send(data); + }, - prefManager.setCharPref("data",null); - prefManager.setBoolPref("data_check", false); - if(timer) { - clearTimeout(timer); - } - timer =setTimeout(PandoraChrome.fn.main , 1000); - } - - else{ - prefManager.setBoolPref("data_check", true); + handleError: function() { + //alert("error"); + prefManager.setCharPref("data", null); + prefManager.setBoolPref("data_check", false); + if (timer) { + clearTimeout(timer); + } + timer = setTimeout(PandoraChrome.fn.main, 1000); + }, - prefManager.setCharPref("data",doc); - PandoraChrome.fn.getEvents(doc); - } - } - }, + handleResponse: function() { + var doc = req.responseText; + if (doc == "auth error") { + prefManager.setCharPref("data", null); + prefManager.setBoolPref("data_check", false); + if (timer) { + clearTimeout(timer); + } + timer = setTimeout(PandoraChrome.fn.main, 1000); + } else { + var n = doc.search("404 Not Found"); + if (n > 0) { + prefManager.setCharPref("data", null); + prefManager.setBoolPref("data_check", false); + if (timer) { + clearTimeout(timer); + } + timer = setTimeout(PandoraChrome.fn.main, 1000); + } else { + prefManager.setBoolPref("data_check", true); - getEvents: function (reply){ - if(reply.length>100){ - all_event_array=reply.split("\n"); - allEvents=PandoraChrome.fn.divideArray(all_event_array); - if(oldEvents.length==0){ - oldEvents=allEvents; - } + prefManager.setCharPref("data", doc); + PandoraChrome.fn.getEvents(doc); + } + } + }, - - newEvents=PandoraChrome.fn.fetchNewEvents(allEvents,oldEvents); - if(newEvents.length!=0){ - for(var k=0;k0){ - PandoraChrome.fn.showBadge(prefManager.getIntPref("new_events")); - } - else{ - PandoraChrome.fn.hideBadge(); - } - - - - if(timer) { - clearTimeout(timer); - } - timer =setTimeout(PandoraChrome.fn.main , prefManager.getIntPref("refresh")*1000 ); - } - }, - - showNotification: function(eventId){ - //alert("notify"+eventId); - if(prefManager.getBoolPref("sound_alert")){ - if(newEvents[eventId][19]=="Critical"){ - Sounds.playSound(prefManager.getIntPref("critical")); - } - if(newEvents[eventId][19]=="Informational"){ - Sounds.playSound(prefManager.getIntPref("informational")); - } - if(newEvents[eventId][19]=="Maintenance"){ - Sounds.playSound(prefManager.getIntPref("maintenance")); - } - if(newEvents[eventId][19]=="Normal"){ - Sounds.playSound(prefManager.getIntPref("normal")); - } - if(newEvents[eventId][19]=="Warning"){ - Sounds.playSound(prefManager.getIntPref("warning")); - } - - } - - var newEve = document.getElementById('newEvent'); - newEve.label="Last Event : "+newEvents[eventId][6]; - var id; - if(newEvents[eventId][9]==0){ - id="."; - } - else { - id= " in the module with Id "+ newEvents[eventId][9] + "."; - } - - var event = newEvents[eventId][14]+" : "+newEvents[eventId][17]+". Event occured at "+ newEvents[eventId][5]+id; - newEve.tooltipText=event; - $('#newEvent').show(); - return; - }, - - - hideNotification:function(){ - //alert("Hide Notif"); - $('#newEvent').hide(); - }, - - - showBadge: function (txt) { - //alert(txt); - var updateCount = document.getElementById('temp'); - updateCount.setAttribute("style","cursor:pointer; font-size:11px; color:#123863; font-weight:bold; display:none;") ; - updateCount.label=txt; - $('#temp').show(); - }, - - hideBadge: function () { - var updateCount = document.getElementById('temp'); - //alert("hide B"); - $('#temp').hide(); - }, - - divideArray: function (e_array){ - var Events=new Array(); - for(var i=0;i' + title + '
' + event + ''; - + getEvents: function(reply) { + if (reply.length > 100) { + all_event_array = reply.split("\n"); + allEvents = PandoraChrome.fn.divideArray(all_event_array); + if (oldEvents.length == 0) { + oldEvents = allEvents; } - }; -}(); + newEvents = PandoraChrome.fn.fetchNewEvents(allEvents, oldEvents); + if (newEvents.length != 0) { + for (var k = 0; k < newEvents.length; k++) { + var temp = prefManager.getIntPref("new_events") + 1; + prefManager.setIntPref("new_events", temp); + PandoraChrome.fn.showNotification(k); + PandoraChrome.fn.showBadge(prefManager.getIntPref("new_events")); + } + } + oldEvents = allEvents; + if (prefManager.getIntPref("new_events") > 0) { + PandoraChrome.fn.showBadge(prefManager.getIntPref("new_events")); + } else { + PandoraChrome.fn.hideBadge(); + } + + if (timer) { + clearTimeout(timer); + } + timer = setTimeout( + PandoraChrome.fn.main, + prefManager.getIntPref("refresh") * 1000 + ); + } + }, + + showNotification: function(eventId) { + //alert("notify"+eventId); + if (prefManager.getBoolPref("sound_alert")) { + if (newEvents[eventId][19] == "Critical") { + Sounds.playSound(prefManager.getIntPref("critical")); + } + if (newEvents[eventId][19] == "Informational") { + Sounds.playSound(prefManager.getIntPref("informational")); + } + if (newEvents[eventId][19] == "Maintenance") { + Sounds.playSound(prefManager.getIntPref("maintenance")); + } + if (newEvents[eventId][19] == "Normal") { + Sounds.playSound(prefManager.getIntPref("normal")); + } + if (newEvents[eventId][19] == "Warning") { + Sounds.playSound(prefManager.getIntPref("warning")); + } + } + + var newEve = document.getElementById("newEvent"); + newEve.label = "Last Event : " + newEvents[eventId][6]; + var id; + if (newEvents[eventId][9] == 0) { + id = "."; + } else { + id = " in the module with Id " + newEvents[eventId][9] + "."; + } + + var event = + newEvents[eventId][14] + + " : " + + newEvents[eventId][17] + + ". Event occured at " + + newEvents[eventId][5] + + id; + newEve.tooltipText = event; + $("#newEvent").show(); + return; + }, + + hideNotification: function() { + //alert("Hide Notif"); + $("#newEvent").hide(); + }, + + showBadge: function(txt) { + //alert(txt); + var updateCount = document.getElementById("temp"); + updateCount.setAttribute( + "style", + "cursor:pointer; font-size:11px; color:#123863; font-weight:bold; display:none;" + ); + updateCount.label = txt; + $("#temp").show(); + }, + + hideBadge: function() { + var updateCount = document.getElementById("temp"); + //alert("hide B"); + $("#temp").hide(); + }, + + divideArray: function(e_array) { + var Events = new Array(); + for (var i = 0; i < e_array.length; i++) { + var event = e_array[i].split(";"); + Events.push(event); + } + return Events; + }, + + fetchNewEvents: function(A, B) { + var arrDiff = new Array(); + // alert(A.length); + //alert(B.length); + for (var i = 0; i < A.length; i++) { + var id = false; + for (var j = 0; j < B.length; j++) { + if (A[i][0] == B[j][0]) { + id = true; + break; + } + } + if (!id) { + arrDiff.push(A[i]); + } + } + return arrDiff; + }, + + getNotification: function(eventId) { + var title = newEvents[eventId][6]; + var id; + if (newEvents[eventId][9] == 0) { + id = "."; + } else { + id = " in the module with Id " + newEvents[eventId][9] + "."; + } + + var event = + newEvents[eventId][14] + + " : " + + newEvents[eventId][17] + + ". Event occured at " + + newEvents[eventId][5] + + id; + //var event=newEvents[eventId][14]+' '+newEvents[eventId][17]+' Event occured at:'+ newEvents[eventId][5] +'in the module with Id '+ newEvents[eventId][9]; + return ( + "" + + title + + '
' + + event + + "" + ); + } + }; +})(); /* Add Event Listener */ window.addEventListener("load", PandoraChrome.fn.Onloading(), false); diff --git a/extras/pandora_update_version.sh b/extras/pandora_update_version.sh index 8a16e8e18d..23ea7a4627 100755 --- a/extras/pandora_update_version.sh +++ b/extras/pandora_update_version.sh @@ -143,7 +143,7 @@ done # Darwin dmg installer files echo "Updating DARWIN DMG files..." -sed -i -e "/VERSION/s/=.*/=\"$VERSION\"/" "$AGENT_DARWIN_BUILDER" +sed -i -e "/VERSION/s/=\"7.0NG.*/=\"$VERSION\"/" "$AGENT_DARWIN_BUILDER" sed -i -r "s/(version=\").*(\"\s+onConclusion=)/\1$VERSION\2/g" "$AGENT_DARWIN_DISTR" sed -i -r "s/(CFBundleVersion<\/key>\s*).*(<\/string>)/\1$VERSION\2/g" "$AGENT_DARWIN_PLIST" sed -i -r "s/(CFBundleShortVersionString<\/key>\s*).*(<\/string>)/\1$VERSION\2/g" "$AGENT_DARWIN_PLIST" diff --git a/pandora_agents/unix/DEBIAN/control b/pandora_agents/unix/DEBIAN/control index 727847ab44..ab8076382f 100644 --- a/pandora_agents/unix/DEBIAN/control +++ b/pandora_agents/unix/DEBIAN/control @@ -1,5 +1,5 @@ package: pandorafms-agent-unix -Version: 7.0NG.750 +Version: 7.0NG.750-201202 Architecture: all Priority: optional Section: admin diff --git a/pandora_agents/unix/DEBIAN/make_deb_package.sh b/pandora_agents/unix/DEBIAN/make_deb_package.sh index 62105af82f..350aa46700 100644 --- a/pandora_agents/unix/DEBIAN/make_deb_package.sh +++ b/pandora_agents/unix/DEBIAN/make_deb_package.sh @@ -14,7 +14,7 @@ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -pandora_version="7.0NG.750" +pandora_version="7.0NG.750-201202" echo "Test if you has the tools for to make the packages." whereis dpkg-deb | cut -d":" -f2 | grep dpkg-deb > /dev/null diff --git a/pandora_agents/unix/Darwin/dmg/build_darwin_dmg.sh b/pandora_agents/unix/Darwin/dmg/build_darwin_dmg.sh index 325d149578..95878467ab 100644 --- a/pandora_agents/unix/Darwin/dmg/build_darwin_dmg.sh +++ b/pandora_agents/unix/Darwin/dmg/build_darwin_dmg.sh @@ -22,7 +22,7 @@ fi # DMG package version if [ "$#" -ge 2 ]; then - VERSION="7.0NG.750" + VERSION="$2" else VERSION="7.0NG.750" fi @@ -37,7 +37,7 @@ fi BUILD_DMG="$BUILD_PATH/build" BUILD_TMP="$BUILD_PATH/buildtmp" -FULLNAME="7.0NG.749" +FULLNAME="$DMGNAME-$VERSION.dmg" echo "VERSION-"$VERSION" NAME-"$DMGNAME pushd . cd $LOCALINST diff --git a/pandora_agents/unix/Darwin/dmg/scripts/postinstall b/pandora_agents/unix/Darwin/dmg/scripts/postinstall index 2f76310fee..5b25222a37 100644 --- a/pandora_agents/unix/Darwin/dmg/scripts/postinstall +++ b/pandora_agents/unix/Darwin/dmg/scripts/postinstall @@ -26,11 +26,13 @@ else `/usr/local/share/pandora_agent/inst_utilities/print_conf.pl /usr/local/share/pandora_agent/pandora_agent.conf remote_config $REMOTECFG` # Create agent directories and files - mkdir -p /usr/local/share/pandora_agent/collections - mkdir -p /usr/local/share/pandora_agent/commands + mkdir -p /usr/local/bin/ + mkdir -p /usr/local/share/man/man1/ + mkdir -p /usr/local/share/pandora_agent/collections/ + mkdir -p /usr/local/share/pandora_agent/commands/ mkdir -p /etc/pandora/ - mkdir -p /var/spool/pandora/data_out - mkdir -p /var/log/pandora + mkdir -p /var/spool/pandora/data_out/ + mkdir -p /var/log/pandora/ mv pandora_agent.conf /etc/pandora/ touch /var/log/pandora/pandora_agent.log @@ -70,9 +72,9 @@ ln -s /usr/local/share/pandora_agent/collections /etc/pandora/collections # Copy manuals -cp -f man/man1/pandora_agent.1.gz /usr/local/share/man/man1 +cp -f man/man1/pandora_agent.1.gz /usr/local/share/man/man1/ chmod 644 /usr/local/share/man/man1/pandora_agent.1.gz -cp -f man/man1/tentacle_client.1.gz /usr/local/share/man/man1 +cp -f man/man1/tentacle_client.1.gz /usr/local/share/man/man1/ chmod 644 /usr/local/share/man/man1/tentacle_client.1.gz # Create newsyslog entry diff --git a/pandora_agents/unix/pandora_agent b/pandora_agents/unix/pandora_agent index 2734a367c0..e229ac10da 100755 --- a/pandora_agents/unix/pandora_agent +++ b/pandora_agents/unix/pandora_agent @@ -33,17 +33,8 @@ use IO::Socket; use Sys::Syslog; use Time::Local; -my $YAML = 0; -# Dynamic load. Avoid unwanted behaviour. -eval { - eval 'require YAML::Tiny;1' or die('YAML::Tiny lib not found, commands feature won\'t be available'); -}; -if ($@) { - $YAML = 0; - print STDERR $@; -} else { - $YAML = 1; -} +use lib '/usr/lib/perl5'; +use PandoraFMS::Omnishell; # Agent XML data my $Xml; @@ -55,7 +46,7 @@ my $Sem = undef; my $ThreadSem = undef; use constant AGENT_VERSION => '7.0NG.750'; -use constant AGENT_BUILD => '201015'; +use constant AGENT_BUILD => '201202'; # Agent log default file size maximum and instances use constant DEFAULT_MAX_LOG_SIZE => 600000; @@ -285,20 +276,6 @@ sub error ($) { exit 1; } -################################################################################ -# Try to load extra libraries.c -################################################################################ -sub load_libraries() { - # Dynamic load. Avoid unwanted behaviour. - eval {eval 'require YAML::Tiny;1' or die('YAML::Tiny lib not found, commands feature won\'t be available');}; - if ($@) { - $YAML = 0; - print STDERR $@; - } else { - $YAML = 1; - } -} - ################################################################################ # Erase blank spaces before and after the string ################################################################################ @@ -1084,8 +1061,6 @@ sub fix_directory ($) { return $dir . $char; } - - ################################################################################ # Sends a file to the server. ################################################################################ @@ -1488,336 +1463,6 @@ sub check_collections () { } } -################################################################################ -# Check for remote commands defined. -################################################################################ -sub prepare_commands { - if ($YAML == 0) { - log_message( - 'error', - 'Cannot use commands without YAML dependency, please install it.' - ); - return; - } - - # Force configuration file read. - my @commands = read_config('cmd_file'); - - if (empty(\@commands)) { - $Conf{'commands'} = {}; - } else { - foreach my $rcmd (@commands) { - $Conf{'commands'}->{trim($rcmd)} = {}; - } - } - - # Cleanup old commands. Not registered. - cleanup_old_commands(); - - foreach my $ref (keys %{$Conf{'commands'}}) { - my $file_content; - my $download = 0; - my $rcmd_file = $ConfDir.'/commands/'.$ref.'.rcmd'; - - # Check for local .rcmd.done files - if (-e $rcmd_file.'.done') { - # Ignore. - delete $Conf{'commands'}->{$ref}; - next; - } - - # Search for local .rcmd file - if (-e $rcmd_file) { - my $remote_md5_file = $Conf{'temporal'}.'/'.$ref.'.md5'; - - $file_content = read_file($rcmd_file); - if (recv_file($ref.'.md5', $remote_md5_file) != 0) { - # Remote file could not be retrieved, skip. - delete $Conf{'commands'}->{$ref}; - next; - } - - my $local_md5 = md5($file_content); - my $remote_md5 = md5(read_file($remote_md5_file)); - - if ($local_md5 ne $remote_md5) { - # Must be downloaded again. - $download = 1; - } - } else { - $download = 1; - } - - # Search for remote .rcmd file - if ($download == 1) { - # Download .rcmd file - if (recv_file($ref.'.rcmd') != 0) { - # Remote file could not be retrieved, skip. - delete $Conf{'commands'}->{$ref}; - next; - } else { - # Success - move($Conf{'temporal'}.'/'.$ref.'.rcmd', $rcmd_file); - } - } - - # Parse and prepare in memory skel. - eval { - $Conf{'commands'}->{$ref} = YAML::Tiny->read($rcmd_file); - }; - if ($@) { - # Failed. - log_message('error', 'Failed to decode command. ' . "\n".$@); - delete $Conf{'commands'}->{$ref}; - next; - } - - } -} - -################################################################################ -# Command report. -################################################################################ -sub report_command { - my ($ref, $err_level) = @_; - - # Retrieve content from .stdout and .stderr - my $stdout_file = $Conf{'temporal'}.'/'.$ref.'.stdout'; - my $stderr_file = $Conf{'temporal'}.'/'.$ref.'.stderr'; - - my $return; - eval { - $return = { - 'error_level' => $err_level, - 'stdout' => read_file($stdout_file), - 'stderr' => read_file($stderr_file), - }; - - $return->{'name'} = $Conf{'commands'}->{$ref}->[0]->{'name'}; - }; - if ($@) { - log_message('error', 'Failed to report command output. ' . $@); - } - - # Cleanup - unlink($stdout_file) if (-e $stdout_file); - unlink($stderr_file) if (-e $stderr_file); - - # Mark command as done. - open (my $R_FILE, '> '.$ConfDir.'/commands/'.$ref.'.rcmd.done'); - print $R_FILE $err_level; - close($R_FILE); - - - $return->{'stdout'} = '' unless defined ($return->{'stdout'}); - $return->{'stderr'} = '' unless defined ($return->{'stderr'}); - - return $return; -} - -################################################################################ -# Cleanup unreferenced rcmd and rcmd.done files. -################################################################################ -sub cleanup_old_commands { - # Cleanup old .rcmd and .rcmd.done files. - my %registered = map { $_.'.rcmd' => 1 } keys %{$Conf{'commands'}}; - if(opendir(my $dir, $ConfDir.'/commands/')) { - while (my $item = readdir($dir)) { - - # Skip other files. - next if ($item !~ /\.rcmd$/); - - # Clean .rcmd.done file if its command is not referenced in conf. - if (!defined($registered{$item})) { - if (-e $ConfDir.'/commands/'.$item) { - unlink($ConfDir.'/commands/'.$item); - } - if (-e $ConfDir.'/commands/'.$item.'.done') { - unlink($ConfDir.'/commands/'.$item.'.done'); - } - } - } - - # Close dir. - closedir($dir); - } - -} - -################################################################################ -# Executes a command using defined timeout. -################################################################################ -sub execute_command_timeout { - my ($cmd, $timeout) = @_; - - if (!defined($timeout) - || !looks_like_number($timeout) - || $timeout <= 0 - ) { - `$cmd`; - return $?>>8; - } - - my $remaining_timeout = $timeout; - - my $RET; - my $output; - - my $pid = open ($RET, "-|"); - if (!defined($pid)) { - # Failed to fork. - log_message('error', '[command] Failed to fork.'); - return undef; - } - if ($pid == 0) { - # Child. - my $ret; - eval { - local $SIG{ALRM} = sub { die "timeout\n" }; - alarm $timeout; - `$cmd`; - alarm 0; - }; - - my $result = ($?>>8); - return $result; - - # Exit child. - # Child finishes. - exit; - - } else { - # Parent waiting. - while( --$remaining_timeout > 0 ){ - if (wait == -1) { - last; - } - # Wait child up to timeout seconds. - sleep 1; - } - } - - if ($remaining_timeout > 0) { - # Retrieve output from child. - $output = do { local $/; <$RET> }; - $output = $output>>8; - } - else { - # Timeout expired. - return 124; - } - - close($RET); - - return $output; -} - -################################################################################ -# Executes a block of commands, returns error level, leaves output in -# redirection set by $std_files. E.g: -# $std_files = ' >> /tmp/stdout 2>> /tmp/stderr -################################################################################ -sub execute_command_block { - my ($commands, $std_files, $timeout, $retry) = @_; - - return 0 unless defined($commands); - - my $retries = $retry; - - $retries = 1 unless looks_like_number($retries) && $retries > 0; - - my $err_level = 0; - $std_files = '' unless defined ($std_files); - - if (ref($commands) ne "ARRAY") { - return 0 if $commands eq ''; - - do { - $err_level = execute_command_timeout( - "($commands) $std_files", - $timeout - ); - - # Do not retry if success. - last if looks_like_number($err_level) && $err_level == 0; - } while ((--$retries) > 0); - - } else { - foreach my $comm (@{$commands}) { - next unless defined($comm); - $retries = $retry; - $retries = 1 unless looks_like_number($retries) && $retries > 0; - - do { - $err_level = execute_command_timeout( - "($comm) $std_files", - $timeout - ); - - # Do not retry if success. - $retries = 0 if looks_like_number($err_level) && $err_level == 0; - - } while ((--$retries) > 0); - - # Do not continue evaluating block if failed. - last unless ($err_level == 0); - } - } - - return $err_level; -} - -################################################################################ -# Evalate given command. -################################################################################ -sub evaluate_command { - my ($ref) = @_; - - # Not found. - return unless defined $Conf{'commands'}->{$ref}; - - # Already completed. - return if (-e $ConfDir.'/commands/'.$ref.'.rcmd.done'); - - # [0] because how library works. - my $cmd = $Conf{'commands'}->{$ref}->[0]; - - my $std_files = ' >> '.$Conf{'temporal'}.'/'.$ref.'.stdout '; - $std_files .= ' 2>> '.$Conf{'temporal'}.'/'.$ref.'.stderr '; - - # Check preconditions - my $err_level; - - $err_level = execute_command_block( - $cmd->{'preconditions'}, - $std_files, - $cmd->{'timeout'} - ); - - # Precondition not satisfied. - return report_command($ref, $err_level) unless ($err_level == 0); - - # Main run. - $err_level = execute_command_block( - $cmd->{'script'}, - $std_files, - $cmd->{'timeout'} - ); - - # Script not success. - return report_command($ref, $err_level) unless ($err_level == 0); - - # Check postconditions - $err_level = execute_command_block( - $cmd->{'postconditions'}, - $std_files, - $cmd->{'timeout'} - ); - - # Return results. - return report_command($ref, $err_level); -} - ################################################################################ # Sleep function ################################################################################ @@ -3435,9 +3080,10 @@ my $main_agent = -1; # base time to start eatch iteration with the same interval. my $iter_base_time = time(); $LogFileIdx = -1; + # Loop while (1) { - load_libraries(); + my $omnishell; if (-e $Conf{'logfile'} && (stat($Conf{'logfile'}))[7] > $Conf{'logsize'}) { rotate_log(); @@ -3453,8 +3099,18 @@ while (1) { # Check file collections check_collections () unless ($Conf{'debug'} eq '1'); - # Check scheduled commands - prepare_commands() unless ($Conf{'debug'} eq '1'); + eval { + # Omnishell controller. + $omnishell = new PandoraFMS::Omnishell( + { + %Conf, + 'ConfDir' => $ConfDir + } + ); + }; + if ($@) { + log_message('error', "Omnishell process error: ".$@); + } # Launch broker agents @BrokerPid = (); @@ -3587,18 +3243,22 @@ while (1) { if (ref ($Conf{'commands'}) eq "HASH") { foreach my $command (keys %{$Conf{'commands'}}) { - my $result = evaluate_command($command); - if (ref($result) eq "HASH") { - # Process command result. - $Xml .= "\n"; - $Xml .= " \n"; - $Xml .= " {'name'}."]]>\n"; - $Xml .= " \n"; - $Xml .= " {'error_level'}."]]>\n"; - $Xml .= " {'stdout'}."]]>\n"; - $Xml .= " {'stderr'}."]]>\n"; - $Xml .= " \n"; - $Xml .= "\n"; + eval { + if ($Conf{'debug'} eq '1') { + log_message('debug', 'Running omnishell commmand ['.$command.']'); + } + + my $output = $omnishell->runCommand($command, 'xml'); + if (!empty($output)) { + $Xml .= $output; + } else { + if ($Conf{'debug'} eq '1') { + log_message('error', 'Omnishell result: '.$omnishell->get_last_error()); + } + } + }; + if ($@) { + log_message('error', 'Omnishell error: '.$@); } } } diff --git a/pandora_agents/unix/pandora_agent.redhat.spec b/pandora_agents/unix/pandora_agent.redhat.spec index 817e89d6eb..aec512fb71 100644 --- a/pandora_agents/unix/pandora_agent.redhat.spec +++ b/pandora_agents/unix/pandora_agent.redhat.spec @@ -3,7 +3,7 @@ # %define name pandorafms_agent_unix %define version 7.0NG.750 -%define release 1 +%define release 201202 Summary: Pandora FMS Linux agent, PERL version Name: %{name} diff --git a/pandora_agents/unix/pandora_agent.spec b/pandora_agents/unix/pandora_agent.spec index 01265b910d..3f605ab943 100644 --- a/pandora_agents/unix/pandora_agent.spec +++ b/pandora_agents/unix/pandora_agent.spec @@ -3,7 +3,7 @@ # %define name pandorafms_agent_unix %define version 7.0NG.750 -%define release 1 +%define release 201202 Summary: Pandora FMS Linux agent, PERL version Name: %{name} diff --git a/pandora_agents/unix/pandora_agent_installer b/pandora_agents/unix/pandora_agent_installer index f6cfadb186..3ebcd9f8b7 100755 --- a/pandora_agents/unix/pandora_agent_installer +++ b/pandora_agents/unix/pandora_agent_installer @@ -10,7 +10,7 @@ # ********************************************************************** PI_VERSION="7.0NG.750" -PI_BUILD="201015" +PI_BUILD="201202" OS_NAME=`uname -s` FORCE=0 diff --git a/pandora_agents/win32/bin/util/omnishell_client.exe b/pandora_agents/win32/bin/util/omnishell_client.exe new file mode 100755 index 0000000000..f0420231e3 Binary files /dev/null and b/pandora_agents/win32/bin/util/omnishell_client.exe differ diff --git a/pandora_agents/win32/installer/pandora.mpi b/pandora_agents/win32/installer/pandora.mpi index cf61454766..b31ae50202 100644 --- a/pandora_agents/win32/installer/pandora.mpi +++ b/pandora_agents/win32/installer/pandora.mpi @@ -186,7 +186,7 @@ UpgradeApplicationID {} Version -{201015} +{201202} ViewReadme {Yes} @@ -2387,7 +2387,7 @@ Windows,BuildSeparateArchives {No} Windows,Executable -{<%AppName%>-Setup<%Ext%>} +{<%AppName%>-<%Version%>-Setup<%Ext%>} Windows,FileDescription {<%AppName%> <%Version%> Setup} diff --git a/pandora_agents/win32/omnishell/omnishell_client.pl b/pandora_agents/win32/omnishell/omnishell_client.pl new file mode 100644 index 0000000000..1a684e5448 --- /dev/null +++ b/pandora_agents/win32/omnishell/omnishell_client.pl @@ -0,0 +1,93 @@ +#!/usr/bin/perl +################################################################################ +# Pandora FMS Omnishell client. +# +# (c) Fco de Borja Sánchez +# +# Usage: omnishell_client "C:\Program Files\pandora_agent\pandora_agent.conf" +# +################################################################################ +use strict; +use warnings; + +use File::Basename; +use lib '/usr/lib/perl5'; +use PandoraFMS::PluginTools; +use PandoraFMS::Omnishell; + +################################################################################ +# Definitions +################################################################################ +my $HELP=< [-debug 1] + + Where is your Pandora FMS Agent configuration. + *Recommended: use full path. + + Use -debug 1 to get information extra in STDERR + +EO_H + +################################################################################ +# Parse commands. +################################################################################ +sub read_commands { + my ($config, $exp, $line, $file) = @_; + + if (empty($config->{'commands'})) { + $config->{'commands'} = {}; + } + + my ($ref) = $line =~ /$exp\s+(.*)/; + $config->{'commands'}->{trim($ref)} = {}; + + return $config; +} + + +################################################################################ +# MAIN +################################################################################ +my $ConfFile = $ARGV[0]; + +my $config = read_configuration({},' ', [ + { + 'exp' => 'cmd_file', + 'target' => \&read_commands + }, +]); + +if (!defined($ConfFile) || !-e $ConfFile) { + print $HELP; + exit 1; +} + +if(!-d dirname($ConfFile).'\commands') { + mkdir(dirname($ConfFile).'\commands'); +} + +eval { + # Check scheduled commands + my $omnishell = new PandoraFMS::Omnishell( + { + %{$config}, + 'ConfDir' => dirname($ConfFile) + } + ); + + if (empty($omnishell->run('xml')) && is_enabled($config->{'debug'}) ) { + print STDERR $omnishell->get_last_error()."\n"; + } +}; +if ($@) { + if (is_enabled($config->{'debug'})) { + print STDERR $@."\n"; + } + exit 1; +} + +exit 0; \ No newline at end of file diff --git a/pandora_agents/win32/pandora.cc b/pandora_agents/win32/pandora.cc index 8f185cd0dc..a2caf79ae2 100644 --- a/pandora_agents/win32/pandora.cc +++ b/pandora_agents/win32/pandora.cc @@ -30,7 +30,7 @@ using namespace Pandora; using namespace Pandora_Strutils; #define PATH_SIZE _MAX_PATH+1 -#define PANDORA_VERSION ("7.0NG.750(Build 201015)") +#define PANDORA_VERSION ("7.0NG.750(Build 201202)") string pandora_path; string pandora_dir; diff --git a/pandora_agents/win32/pandora_windows_service.cc b/pandora_agents/win32/pandora_windows_service.cc index 3dd80d2a15..360673363f 100644 --- a/pandora_agents/win32/pandora_windows_service.cc +++ b/pandora_agents/win32/pandora_windows_service.cc @@ -1704,7 +1704,7 @@ Pandora_Windows_Service::checkConfig (string file) { } int -Pandora_Windows_Service::sendXml (Pandora_Module_List *modules) { +Pandora_Windows_Service::sendXml (Pandora_Module_List *modules, string extra /* = ""*/) { int rc = 0, rc_sec = 0, xml_buffer; string data_xml; string xml_filename, random_integer; @@ -1785,10 +1785,13 @@ Pandora_Windows_Service::sendXml (Pandora_Module_List *modules) { modules->goNext (); } } - + + /* Write extra content (omnishell, for instance) */ + data_xml += extra; + /* Close the XML header */ data_xml += ""; - + /* Generate temporal filename */ random_integer = inttostr (rand()); tmp_filename = conf->getValue ("agent_name"); @@ -2018,7 +2021,7 @@ Pandora_Windows_Service::pandora_run () { void Pandora_Windows_Service::pandora_run (int forced_run) { Pandora_Agent_Conf *conf = NULL; - string server_addr, conf_file, *all_conf; + string server_addr, conf_file, *all_conf, omnishell_output, omnishell_path; int startup_delay = 0; int i, num; static bool startup = true; @@ -2055,6 +2058,15 @@ Pandora_Windows_Service::pandora_run (int forced_run) { this->checkCollections (); } + + /* Execute omnishell commands */ + omnishell_path = '"'+Pandora::getPandoraInstallDir (); + omnishell_path += "util\\omnishell_client.exe\" \"" + conf_file+"\""; + if (getPandoraDebug () != false) { + pandoraLog ("Omnishell: Running"); + } + omnishell_output = getValueFromCmdExec(omnishell_path.c_str(), 6000000); + server_addr = conf->getValue ("server_ip"); execution_number++; @@ -2126,7 +2138,7 @@ Pandora_Windows_Service::pandora_run (int forced_run) { // Send the XML if (!server_addr.empty ()) { - this->sendXml (this->modules); + this->sendXml (this->modules, omnishell_output); } } diff --git a/pandora_agents/win32/pandora_windows_service.h b/pandora_agents/win32/pandora_windows_service.h index 3f9a89d685..aa5427ab8c 100644 --- a/pandora_agents/win32/pandora_windows_service.h +++ b/pandora_agents/win32/pandora_windows_service.h @@ -117,7 +117,7 @@ namespace Pandora { const char *svc_description); void start (); - int sendXml (Pandora_Module_List *modules); + int sendXml (Pandora_Module_List *modules, string extra = ""); void sendBufferedXml (string path, copy_func_p copy_func, bool secondary_buffer); Pandora_Agent_Conf *getConf (); string getEHKey (string ehorus_conf); diff --git a/pandora_agents/win32/versioninfo.rc b/pandora_agents/win32/versioninfo.rc index a1ec2dc7bb..a8ff1c1cf5 100644 --- a/pandora_agents/win32/versioninfo.rc +++ b/pandora_agents/win32/versioninfo.rc @@ -11,7 +11,7 @@ BEGIN VALUE "LegalCopyright", "Artica ST" VALUE "OriginalFilename", "PandoraAgent.exe" VALUE "ProductName", "Pandora FMS Windows Agent" - VALUE "ProductVersion", "(7.0NG.750(Build 201015))" + VALUE "ProductVersion", "(7.0NG.750(Build 201202))" VALUE "FileVersion", "1.0.0.0" END END diff --git a/pandora_console/DEBIAN/control b/pandora_console/DEBIAN/control index 1f12c293fb..a4c9c5a2be 100644 --- a/pandora_console/DEBIAN/control +++ b/pandora_console/DEBIAN/control @@ -1,5 +1,5 @@ package: pandorafms-console -Version: 7.0NG.750 +Version: 7.0NG.750-201202 Architecture: all Priority: optional Section: admin diff --git a/pandora_console/DEBIAN/make_deb_package.sh b/pandora_console/DEBIAN/make_deb_package.sh index 1f28341bb7..0dc958f481 100644 --- a/pandora_console/DEBIAN/make_deb_package.sh +++ b/pandora_console/DEBIAN/make_deb_package.sh @@ -14,7 +14,7 @@ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -pandora_version="7.0NG.750" +pandora_version="7.0NG.750-201202" package_pear=0 package_pandora=1 diff --git a/pandora_console/extensions/agents_alerts.php b/pandora_console/extensions/agents_alerts.php index 4fd7be94ae..38f55cc623 100755 --- a/pandora_console/extensions/agents_alerts.php +++ b/pandora_console/extensions/agents_alerts.php @@ -1,651 +1,91 @@ 'ANY(SELECT id_agente FROM tagente WHERE id_grupo = '.$group]; - - db_process_sql_update('tagente_modulo', ['flag' => 1], $where); - } else { - db_pandora_audit('ACL Violation', 'Trying to set flag for groups'); - include 'general/noaccess.php'; + // Ajax variables. + $pageName = '[AgentsAlerts]'; + // Control call flow. + try { + // User access and validation is being processed on class constructor. + $obj = new AgentsAlerts(); + } catch (Exception $e) { + if (is_ajax() === true) { + echo json_encode(['error' => $pageName.$e->getMessage() ]); exit; - } - } - - if ($config['realtimestats'] == 0) { - $updated_info = __('Last update').' : '.ui_print_timestamp(db_get_sql('SELECT min(utimestamp) FROM tgroup_stat'), true); - } else { - // $updated_info = __("Updated at realtime"); - $updated_info = ''; - } - - $updated_time = $updated_info; - $create_alert = (int) get_parameter('create_alert', 0); - - if ($create_alert) { - $template2 = get_parameter('template'); - $module_action_threshold = get_parameter('module_action_threshold'); - - $id_alert = alerts_create_alert_agent_module($create_alert, $template2); - - if ($id_alert !== false) { - $action_select = get_parameter('action_select', 0); - - if ($action_select != 0) { - $values = []; - $values['fires_min'] = 0; - $values['fires_max'] = 0; - $values['module_action_threshold'] = (int) get_parameter('module_action_threshold'); - - alerts_add_alert_agent_module_action($id_alert, $action_select, $values); - } - } - } - - $refr = (int) get_parameter('refr', 30); - // By default 30 seconds - $show_modules = (bool) get_parameter('show_modules', 0); - $group_id = get_parameter('group_id', 0); - $offset = get_parameter('offset', 0); - $hor_offset = get_parameter('hor_offset', 0); - $block = 20; - - $groups = users_get_groups(); - - $filter_groups .= ''.__('Group').''; - $filter_groups .= '
'; - $filter_groups .= html_print_select_groups(false, 'AR', true, 'group_id', $group_id, false, '', '', true, false, true, '', false, 'margin-right: 10px; margin-top: 5px;'); - $filter_groups .= '
'; - - $check = ''.__('Show modules without alerts').''; - $check .= html_print_checkbox('slides_ids[]', $d['id'], $show_modules, true, false, '', true); - - $comborefr = '
'; - $comborefr .= ''.__('Refresh').''; - $comborefr .= html_print_select( - [ - '30' => '30 '.__('seconds'), - (string) SECONDS_1MINUTE => __('1 minute'), - (string) SECONDS_2MINUTES => __('2 minutes'), - (string) SECONDS_5MINUTES => __('5 minutes'), - (string) SECONDS_10MINUTES => __('10 minutes'), - ], - 'refr', - (int) get_parameter('refr', 0), - $script = 'this.form.submit()', - '', - 0, - true, - false, - false, - '', - false, - 'width: 100px; margin-right: 10px; margin-top: 5px;' - ); - $comborefr .= '
'; - - if ($config['pure'] == 0) { - $fullscreen['text'] = ''.html_print_image('images/full_screen.png', true, ['title' => __('Full screen mode')]).''; - } else { - $fullscreen['text'] = ''.html_print_image('images/normal_screen.png', true, ['title' => __('Back to normal mode')]).''; - $config['refr'] = $refr; - } - - $onheader = [ - 'updated_time' => $updated_time, - 'fullscreen' => $fullscreen, - 'combo_groups' => $filter_groups, - ]; - - if ($config['pure'] == 1) { - $onheader['combo_refr'] = $comborefr; - } - - // Header. - ui_print_page_header( - __('Agents/Alerts'), - 'images/op_alerts.png', - false, - '', - false, - $updated_time - ); - - // Old style table, we need a lot of special formatting,don't use table function - // Prepare old-style table - echo ''; - echo ''; - echo ''; - echo ''; - if ($config['pure'] == 1) { - echo ''; - } - - echo ''; - echo ''; - echo '
'.$filter_groups.''.$check.''.$comborefr.' '.__('Full screen').''.$fullscreen['text'].'
'; - - if ($show_modules) { - if ($group_id > 0) { - $grupo = " AND tagente.id_grupo = $group_id"; } else { - $grupo = ''; + echo $pageName.$e->getMessage(); } - $offset_modules = get_parameter('offset', 0); - $sql_count = "SELECT COUNT(tagente_modulo.nombre) FROM tagente_modulo - INNER JOIN tagente ON tagente.id_agente = tagente_modulo.id_agente - WHERE id_agente_modulo NOT IN (SELECT id_agent_module FROM talert_template_modules) - $grupo"; - $count_agent_module = db_get_all_rows_sql($sql_count); - - $sql = "SELECT tagente.alias, tagente_modulo.nombre, - tagente_modulo.id_agente_modulo FROM tagente_modulo - INNER JOIN tagente ON tagente.id_agente = tagente_modulo.id_agente - WHERE id_agente_modulo NOT IN (SELECT id_agent_module FROM talert_template_modules) - $grupo LIMIT 20 OFFSET $offset_modules"; - $agent_modules = db_get_all_rows_sql($sql); - - ui_pagination( - $count_agent_module[0]['COUNT(tagente_modulo.nombre)'], - ui_get_url_refresh(), - 0, - 0, - false, - 'offset', - true, - '', - '', - false, - 'alerts_modules' - ); - - $table->width = '100%'; - $table->class = 'databox data'; - $table->id = 'table_agent_module'; - $table->data = []; - - $table->head[0] = __('Agents'); - $table->head[1] = __('Modules'); - $table->head[2] = __('Actions'); - - $table->style[0] = 'width: 25%;'; - $table->style[1] = 'width: 33%;'; - $table->style[2] = 'width: 33%;'; - - foreach ($agent_modules as $agent_module) { - $data[0] = io_safe_output($agent_module['alias']); - $data[1] = io_safe_output($agent_module['nombre']); - $uniqid = $agent_module['id_agente_modulo']; - $data[2] = "".html_print_image('images/add_mc.png', true).''; - array_push($table->data, $data); - - $table2->width = '100%'; - $table2->id = 'table_add_alert'; - $table2->class = 'databox filters'; - $table2->data = []; - // $data[0] = - $table2->data[0][0] = __('Actions'); - - $groups_user = users_get_groups($config['id_user']); - if (!empty($groups_user)) { - $groups = implode(',', array_keys($groups_user)); - $sql = "SELECT id, name FROM talert_actions WHERE id_group IN ($groups)"; - $actions = db_get_all_rows_sql($sql); - } - - $table2->data[0][1] = html_print_select( - index_array($actions, 'id', 'name'), - 'action_select', - '', - '', - __('Default action'), - '0', - true, - '', - true, - '', - false, - 'width: 250px;' - ); - $table2->data[0][1] .= ''; - if (check_acl($config['id_user'], 0, 'LM')) { - $table2->data[0][1] .= ''; - $table2->data[0][1] .= html_print_image('images/add.png', true); - $table2->data[0][1] .= ''.__('Create Action').''; - $table2->data[0][1] .= ''; - } - - $table2->data[1][0] = __('Template'); - $own_info = get_user_info($config['id_user']); - if ($own_info['is_admin'] || check_acl($config['id_user'], 0, 'PM')) { - $templates = alerts_get_alert_templates(false, ['id', 'name']); - } else { - $usr_groups = users_get_groups($config['id_user'], 'LW', true); - $filter_groups = ''; - $filter_groups = implode(',', array_keys($usr_groups)); - $templates = alerts_get_alert_templates(['id_group IN ('.$filter_groups.')'], ['id', 'name']); - } - - $table2->data[1][1] = html_print_select( - index_array($templates, 'id', 'name'), - 'template', - '', - '', - __('Select'), - 0, - true, - false, - true, - '', - false, - 'width: 250px;' - ); - $table2->data[1][1] .= ' '; - if (check_acl($config['id_user'], 0, 'LM')) { - $table2->data[1][1] .= ''; - $table2->data[1][1] .= html_print_image('images/add.png', true); - $table2->data[1][1] .= ''.__('Create Template').''; - $table2->data[1][1] .= ''; - } - - $table2->data[2][0] = __('Threshold'); - $table2->data[2][1] = html_print_input_text('module_action_threshold', '0', '', 5, 7, true); - $table2->data[2][1] .= ' '.__('seconds'); - - $content2 = '
'; - $content2 .= html_print_table($table2, true); - - $content2 .= '
'; - $content2 .= html_print_submit_button(__('Add alert'), 'add', false, 'class="sub wand"', true); - $content2 .= html_print_input_hidden('create_alert', $uniqid, true); - $content2 .= '
'; - - $module_name = ui_print_truncate_text(io_safe_output($agent_module['nombre']), 40, false, true, false, '…', false); - echo ''; - } - - html_print_table($table); - } else { - $filter = [ - 'offset' => (int) $offset, - 'limit' => (int) $config['block_size'], - ]; - $filter_count = []; - - if ($group_id > 0) { - $filter['id_grupo'] = $group_id; - $filter_count['id_grupo'] = $group_id; - } - - // Get the id of all agents with alerts - $sql = 'SELECT DISTINCT(id_agente) - FROM tagente_modulo - WHERE id_agente_modulo IN - (SELECT id_agent_module - FROM talert_template_modules)'; - $agents_with_alerts_raw = db_get_all_rows_sql($sql); - - if ($agents_with_alerts_raw === false) { - $agents_with_alerts_raw = []; - } - - $agents_with_alerts = []; - foreach ($agents_with_alerts_raw as $awar) { - $agents_with_alerts[] = $awar['id_agente']; - } - - $filter['id_agente'] = $agents_with_alerts; - $filter_count['id_agente'] = $agents_with_alerts; - - $agents = agents_get_agents($filter); - - $nagents = count(agents_get_agents($filter_count)); - - if ($agents == false) { - ui_print_info_message(['no_close' => true, 'message' => __('There are no agents with alerts') ]); - return; - } - - $all_alerts = agents_get_alerts_simple(); - - if ($config['pure'] == 1) { - $block = count($all_alerts); - } - - $templates = []; - $agent_alerts = []; - foreach ($all_alerts as $alert) { - $templates[$alert['id_alert_template']] = ''; - $agent_alerts[$alert['agent_name']][$alert['id_alert_template']][] = $alert; - } - - // Prepare pagination - ui_pagination( - $nagents, - false, - 0, - 0, - false, - 'offset', - true, - '', - '', - [ - 'count' => '', - 'offset' => 'offset_param', - ], - 'alerts_agents' - ); - - echo ''; - echo ''; - echo "'; - - if ($hor_offset > 0) { - $new_hor_offset = ($hor_offset - $block); - echo "'; - } - - $templates_raw = []; - if (!empty($templates)) { - $sql = sprintf( - 'SELECT id, name - FROM talert_templates - WHERE id IN (%s)', - implode(',', array_keys($templates)) - ); - - $templates_raw = db_get_all_rows_sql($sql); - } - - if (empty($templates_raw)) { - $templates_raw = []; - } - - $alerts = []; - $ntemplates = 0; - foreach ($templates_raw as $temp) { - if (isset($templates[$temp['id']]) && $templates[$temp['id']] == '') { - $ntemplates++; - if ($ntemplates <= $hor_offset || $ntemplates > ($hor_offset + $block)) { - continue; - } - - $templates[$temp['id']] = $temp['name']; - } - } - - foreach ($templates as $tid => $tname) { - if ($tname == '') { - continue; - } - - echo ''; - } - - echo ''; - if (($hor_offset + $block) < $ntemplates) { - $new_hor_offset = ($hor_offset + $block); - echo "'; - } - - foreach ($agents as $agent) { - $alias = db_get_row('tagente', 'id_agente', $agent['id_agente']); - echo ''; - // Name of the agent - echo ''; - - // Alerts of the agent - $anyfired = false; - foreach ($templates as $tid => $tname) { - if ($tname == '') { - continue; - } - - if (isset($agent_alerts[$agent['nombre']][$tid])) { - foreach ($agent_alerts[$agent['nombre']][$tid] as $alert) { - if ($alert['times_fired'] > 0) { - $anyfired = true; - } - } - - $cellstyle = ''; - if ($anyfired) { - $cellstyle = 'background:'.COL_ALERTFIRED.';'; - } - - echo ''; - } - - echo ''; - } - - echo '
".__('Agents').' / '.__('Alert templates').' - ".html_print_image('images/darrowleft.png', true, ['title' => __('Previous templates')]).' '.io_safe_output($tname).'
- ".html_print_image('images/darrowright.png', true, ['title' => __('More templates')]).'
'.$alias['alias'].' '; - - $uniqid = uniqid(); - echo '
'; - - echo count($agent_alerts[$agent['nombre']][$tid]).' '.__('Alerts').' '; - - echo "".html_print_image('images/zoom.png', true).''; - - echo '
'; - - print_alerts_summary_modal_window($uniqid, $agent_alerts[$agent['nombre']][$tid]); - } else { - echo '
'; - } - - echo '
'; - - ui_pagination( - $nagents, - false, - 0, - 0, - false, - 'offset', - true, - 'pagination-bottom', - '', - [ - 'count' => '', - 'offset' => 'offset_param', - ], - 'alerts_agents' - ); + // Stop this execution, but continue 'globally'. + return; } + // AJAX controller. + if (is_ajax() === true) { + $method = get_parameter('method'); + + if (method_exists($obj, $method) === true) { + $obj->{$method}(); + } else { + $obj->error('Method not found. ['.$method.']'); + } + + // Stop any execution. + exit; + } else { + // Run. + $obj->run(); + } } - - -// Print the modal window for the summary of each alerts group -function print_alerts_summary_modal_window($id, $alerts) -{ - $table->width = '98%'; - $table->class = 'info_table'; - $table->data = []; - - $table->head[0] = __('Module'); - $table->head[1] = __('Action'); - $table->head[2] = __('Last fired'); - $table->head[3] = __('Status'); - - foreach ($alerts as $alert) { - $data[0] = modules_get_agentmodule_name($alert['id_agent_module']); - - $actions = alerts_get_alert_agent_module_actions($alert['id']); - - $actionDefault = db_get_value_sql( - ' - SELECT id_alert_action - FROM talert_templates - WHERE id = '.$alert['id_alert_template'] - ); - - $actionText = ''; - - if (!empty($actions)) { - $actionText = '
    '; - foreach ($actions as $action) { - $actionText .= '
  • '.$action['name']; - if ($action['fires_min'] != $action['fires_max']) { - $actionText .= ' ('.$action['fires_min'].' / '.$action['fires_max'].')'; - } - - $actionText .= '

  • '; - } - - $actionText .= '
'; - } else { - if (!empty($actionDefault)) { - $actionText = db_get_sql( - "SELECT name - FROM talert_actions - WHERE id = $actionDefault" - ).' ('.__('Default').')'; - } - } - - $data[1] = $actionText; - $data[2] = ui_print_timestamp($alert['last_fired'], true); - - $status = STATUS_ALERT_NOT_FIRED; - - if ($alert['times_fired'] > 0) { - $status = STATUS_ALERT_FIRED; - $title = __('Alert fired').' '.$alert['internal_counter'].' '.__('time(s)'); - } else if ($alert['disabled'] > 0) { - $status = STATUS_ALERT_DISABLED; - $title = __('Alert disabled'); - } else { - $status = STATUS_ALERT_NOT_FIRED; - $title = __('Alert not fired'); - } - - $data[3] = ui_print_status_image($status, $title, true); - - array_push($table->data, $data); - } - - $content = html_print_table($table, true); - - $agent = modules_get_agentmodule_agent_alias($alerts[0]['id_agent_module']); - $template = alerts_get_alert_template_name($alerts[0]['id_alert_template']); - - echo ''; -} - - -extensions_add_operation_menu_option(__('Agents/Alerts view'), 'estado', null, 'v1r1', 'view'); -extensions_add_main_function('mainAgentsAlerts'); - -ui_require_jquery_file('pandora'); - -?> - - diff --git a/pandora_console/extensions/agents_modules.php b/pandora_console/extensions/agents_modules.php index 8aa032c9a8..eb699b7467 100644 --- a/pandora_console/extensions/agents_modules.php +++ b/pandora_console/extensions/agents_modules.php @@ -26,17 +26,6 @@ function agents_modules_load_js() $ignored_params['refresh'] = ''; ?> - - '; echo ''; echo ''; - // Store servers timezone offset to be retrieved from js + // Store servers timezone offset to be retrieved from js. set_js_value('timezone_offset', date('Z', time())); } -extensions_add_operation_menu_option(__('Realtime graphs'), 'estado', null, 'v1r1', 'view'); +extensions_add_operation_menu_option( + __('Realtime graphs'), + 'estado', + null, + 'v1r1', + 'view' +); extensions_add_main_function('pandora_realtime_graphs'); $db = null; diff --git a/pandora_console/extensions/realtime_graphs/ajax.php b/pandora_console/extensions/realtime_graphs/ajax.php index dea94a5753..a09ef9bb29 100644 --- a/pandora_console/extensions/realtime_graphs/ajax.php +++ b/pandora_console/extensions/realtime_graphs/ajax.php @@ -69,15 +69,34 @@ switch ($graph) { case 'snmp_interface': case 'snmp_module': - $snmp_address = $_POST['snmp_address']; - $snmp_community = $_POST['snmp_community']; - $snmp_ver = $_POST['snmp_ver']; - $snmp_oid = $_POST['snmp_oid']; + $snmp_address = get_parameter('snmp_address', ''); + $snmp_community = get_parameter('snmp_community', ''); + $snmp_ver = get_parameter('snmp_ver', ''); + $snmp_oid = get_parameter('snmp_oid', ''); + $snmp3_auth_user = get_parameter('snmp3_auth_user', ''); + $snmp3_security_level = get_parameter('snmp3_security_level', ''); + $snmp3_auth_method = get_parameter('snmp3_auth_method', ''); + $snmp3_auth_pass = get_parameter('snmp3_auth_pass', ''); + $snmp3_privacy_method = get_parameter('snmp3_privacy_method', ''); + $snmp3_privacy_pass = get_parameter('snmp3_privacy_pass', ''); if (empty($snmp_address) || empty($snmp_oid)) { $data = 0; } else { - $data = get_snmpwalk($snmp_address, $snmp_ver, $snmp_community, '', '', '', '', '', '', 0, $snmp_oid); + $data = get_snmpwalk( + $snmp_address, + $snmp_ver, + $snmp_community, + $snmp3_auth_user, + $snmp3_security_level, + $snmp3_auth_method, + $snmp3_auth_pass, + $snmp3_privacy_method, + $snmp3_privacy_pass, + 0, + $snmp_oid, + $snmp_port + ); $data_index = array_keys($data); $graph_title = $data_index[0]; if (!empty($data)) { diff --git a/pandora_console/extensions/realtime_graphs/realtime_graphs.js b/pandora_console/extensions/realtime_graphs/realtime_graphs.js index b5d6c1eaa8..088f31dbf6 100644 --- a/pandora_console/extensions/realtime_graphs/realtime_graphs.js +++ b/pandora_console/extensions/realtime_graphs/realtime_graphs.js @@ -1,3 +1,4 @@ +/* global $, get_php_value */ (function() { var numberOfPoints = 100; var refresh = parseInt($("#refresh").val()); @@ -14,7 +15,7 @@ container: $("#chartLegend") }, xaxis: { - tickFormatter: function(timestamp, axis) { + tickFormatter: function(timestamp) { var date = new Date(timestamp * 1000); var server_timezone_offset = get_php_value("timezone_offset"); @@ -39,7 +40,7 @@ } }, yaxis: { - tickFormatter: function(value, axis) { + tickFormatter: function(value) { return shortNumber(roundToTwo(value)); } }, @@ -66,10 +67,16 @@ data: { graph: $("#graph :selected").val(), graph_title: $("#graph :selected").html(), - snmp_community: $("#text-snmp_community").val(), - snmp_oid: $("#text-snmp_oid").val(), - snmp_ver: $("#snmp_version :selected").val(), - snmp_address: $("#text-ip_target").val(), + snmp_community: $("#text-community").val(), + snmp_oid: $("#text-starting_oid").val(), + snmp_ver: $("#snmp_browser_version").val(), + snmp_address: $("#text-target_ip").val(), + snmp3_auth_user: $("#text-snmp3_browser_auth_user").val(), + snmp3_security_level: $("#snmp3_browser_security_level").val(), + snmp3_auth_method: $("#snmp3_browser_auth_method").val(), + snmp3_auth_pass: $("#password-snmp3_browser_auth_pass").val(), + snmp3_privacy_method: $("#snmp3_browser_privacy_method").val(), + snmp3_privacy_pass: $("#password-snmp3_browser_privacy_pass").val(), refresh: refresh }, success: function(serie) { @@ -87,7 +94,7 @@ } if (data.length === 0) { - for (i = 0; i < numberOfPoints; i++) { + for (var i = 0; i < numberOfPoints; i++) { var step = i * (refresh / 1000); serie.data.unshift([timestamp - step, 0]); } @@ -123,7 +130,7 @@ var data = plot.getData(); if (data.length === 0) return; - for (i = 0; i < data[0].data.length; i++) { + for (var i = 0; i < data[0].data.length; i++) { data[0].data[i][1] = 0; } if (incremental) lastIncVal = null; diff --git a/pandora_console/extensions/resource_exportation.php b/pandora_console/extensions/resource_exportation.php index 3946ec053d..16cf674ab6 100755 --- a/pandora_console/extensions/resource_exportation.php +++ b/pandora_console/extensions/resource_exportation.php @@ -92,7 +92,11 @@ function output_xml_report($id) $group = db_get_value('nombre', 'tgrupo', 'id_grupo', $report['id_group']); echo '\n"; - $items = db_get_all_rows_field_filter('treport_content', 'id_report', $report['id_report']); + $items = db_get_all_rows_field_filter( + 'treport_content', + 'id_report', + $report['id_report'] + ); foreach ($items as $item) { echo "\n"; echo ''.io_safe_output($item['type'])."\n"; diff --git a/pandora_console/extensions/resource_registration.php b/pandora_console/extensions/resource_registration.php index dae61e3a78..80fed2cf6c 100755 --- a/pandora_console/extensions/resource_registration.php +++ b/pandora_console/extensions/resource_registration.php @@ -37,8 +37,16 @@ function insert_item_report($report_id, $values) ui_print_result_message( $result, - sprintf(__("Success add '%s' item in report '%s'."), $values['type'], $name), - sprintf(__("Error create '%s' item in report '%s'."), $values['type'], $name) + sprintf( + __("Success add '%s' item in report '%s'."), + $values['type'], + $name + ), + sprintf( + __("Error create '%s' item in report '%s'."), + $values['type'], + $name + ) ); } } @@ -55,9 +63,12 @@ function process_upload_xml_report($xml, $group_filter=0) $posible_name = $values['name']; $exist = true; $loops = 30; - // Loops to exit or tries + // Loops to exit or tries. while ($exist && $loops > 0) { - $exist = (bool) db_get_row_filter('treport', ['name' => io_safe_input($posible_name)]); + $exist = (bool) db_get_row_filter( + 'treport', + ['name' => io_safe_input($posible_name)] + ); if ($exist) { $loops--; @@ -74,7 +85,7 @@ function process_upload_xml_report($xml, $group_filter=0) ); break; } else if ($loops != 30) { - ui_print_error_message( + ui_print_warning_message( sprintf( __("Warning create '%s' report, the name exist, the report have a name %s."), $reportElement->name, @@ -89,13 +100,22 @@ function process_upload_xml_report($xml, $group_filter=0) break; } - $id_group = db_get_value('id_grupo', 'tgrupo', 'nombre', $reportElement->group); - if ($id_group === false) { - ui_print_error_message(__("Error the report haven't group.")); - break; + if (isset($reportElement->group) === true + && empty($reportElement->group) === false + ) { + $id_group = db_get_value( + 'id_grupo', + 'tgrupo', + 'nombre', + $reportElement->group + ); + if ($id_group === false) { + ui_print_error_message(__("Error the report haven't group.")); + break; + } } - if (isset($reportElement->description)) { + if (isset($reportElement->description) === true) { $values['description'] = $reportElement->description; } @@ -108,9 +128,19 @@ function process_upload_xml_report($xml, $group_filter=0) ); if ($id_report) { - db_pandora_audit('Report management', 'Create report '.$id_report, false, false); + db_pandora_audit( + 'Report management', + 'Create report '.$id_report, + false, + false + ); } else { - db_pandora_audit('Report management', 'Fail to create report', false, false); + db_pandora_audit( + 'Report management', + 'Fail to create report', + false, + false + ); break; } @@ -119,45 +149,52 @@ function process_upload_xml_report($xml, $group_filter=0) $values = []; $values['id_report'] = $id_report; - if (isset($item['description'])) { + if (isset($item['description']) === true) { $values['description'] = io_safe_input($item['description']); } - if (isset($item['period'])) { + if (isset($item['period']) === true) { $values['period'] = io_safe_input($item['period']); } - if (isset($item['type'])) { + if (isset($item['type']) === true) { $values['type'] = io_safe_input($item['type']); } $agents_item = []; - if (isset($item['agent'])) { + if (isset($item['agent']) === true) { $agents = agents_get_agents( ['id_grupo' => $group_filter], [ 'id_agente', - 'nombre', + 'alias', ] ); - $agent_clean = str_replace(['[', ']'], '', $item['agent']); + $agent_clean = str_replace( + [ + '[', + ']', + ], + '', + io_safe_output($item['agent']) + ); $regular_expresion = ($agent_clean != $item['agent']); foreach ($agents as $agent) { if ($regular_expresion) { - if ((bool) preg_match('/'.$agent_clean.'/', io_safe_output($agent['nombre']))) { - $agents_item[$agent['id_agente']]['name'] = $agent['nombre']; + if ((bool) preg_match('/'.$agent_clean.'/', io_safe_output($agent['alias']))) { + $agents_item[$agent['id_agente']]['name'] = $agent['alias']; } } else { - if ($agent_clean == io_safe_output($agent['nombre'])) { - $agents_item[$agent['id_agente']]['name'] = $agent['nombre']; + if ($agent_clean == io_safe_output($agent['alias'])) { + $agents_item[$agent['id_agente']]['name'] = $agent['alias']; } } } } - if (isset($item['module'])) { + if (isset($item['module']) === true) { $module_clean = str_replace(['[', ']'], '', $item['module']); $regular_expresion = ($module_clean != $item['module']); diff --git a/pandora_console/extras/mr/42.sql b/pandora_console/extras/mr/42.sql index 26f20e0f0a..f4bed54d16 100644 --- a/pandora_console/extras/mr/42.sql +++ b/pandora_console/extras/mr/42.sql @@ -31,4 +31,6 @@ ALTER TABLE `treport` ADD COLUMN `index_render` tinyint(1) NOT NULL DEFAULT 1; ALTER TABLE `treport_template` ADD COLUMN `cover_page_render` tinyint(1) NOT NULL DEFAULT 1; ALTER TABLE `treport_template` ADD COLUMN `index_render` tinyint(1) NOT NULL DEFAULT 1; +UPDATE `tconfig` SET value = '{"0.00000038580247":"Seconds to months","0.00000165343915":"Seconds to weeks","0.00001157407407":"Seconds to days","0.01666666666667":"Seconds to minutes","0.00000000093132":"Bytes to Gigabytes","0.00000095367432":"Bytes to Megabytes","0.00097656250000":"Bytes to Kilobytes","0.00000001653439":"Timeticks to weeks","0.00000011574074":"Timeticks to days"}' WHERE token = 'post_process_custom_values'; + COMMIT; \ No newline at end of file diff --git a/pandora_console/extras/mr/43.sql b/pandora_console/extras/mr/43.sql index 3845154eb1..02cd804410 100644 --- a/pandora_console/extras/mr/43.sql +++ b/pandora_console/extras/mr/43.sql @@ -2,4 +2,10 @@ START TRANSACTION; ALTER TABLE `tagente_modulo` ADD COLUMN `debug_content` varchar(200); +ALTER TABLE `talert_snmp` ADD COLUMN `al_field16` TEXT NOT NULL AFTER `al_field15`; +ALTER TABLE `talert_snmp` ADD COLUMN `al_field17` TEXT NOT NULL AFTER `al_field16`; +ALTER TABLE `talert_snmp` ADD COLUMN `al_field18` TEXT NOT NULL AFTER `al_field17`; +ALTER TABLE `talert_snmp` ADD COLUMN `al_field19` TEXT NOT NULL AFTER `al_field18`; +ALTER TABLE `talert_snmp` ADD COLUMN `al_field20` TEXT NOT NULL AFTER `al_field19`; + COMMIT; \ No newline at end of file diff --git a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql index 5dd93ebf31..4a7b3e4929 100644 --- a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql +++ b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql @@ -1256,11 +1256,16 @@ ALTER TABLE `talert_templates` ADD COLUMN `disable_event` tinyint(1) DEFAULT 0; -- --------------------------------------------------------------------- -- Table `talert_snmp` -- --------------------------------------------------------------------- -ALTER TABLE talert_snmp ADD COLUMN `al_field11` TEXT NOT NULL DEFAULT ""; -ALTER TABLE talert_snmp ADD COLUMN `al_field12` TEXT NOT NULL DEFAULT ""; -ALTER TABLE talert_snmp ADD COLUMN `al_field13` TEXT NOT NULL DEFAULT ""; -ALTER TABLE talert_snmp ADD COLUMN `al_field14` TEXT NOT NULL DEFAULT ""; -ALTER TABLE talert_snmp ADD COLUMN `al_field15` TEXT NOT NULL DEFAULT ""; +ALTER TABLE `talert_snmp` ADD COLUMN `al_field11` TEXT NOT NULL DEFAULT ""; +ALTER TABLE `talert_snmp` ADD COLUMN `al_field12` TEXT NOT NULL DEFAULT ""; +ALTER TABLE `talert_snmp` ADD COLUMN `al_field13` TEXT NOT NULL DEFAULT ""; +ALTER TABLE `talert_snmp` ADD COLUMN `al_field14` TEXT NOT NULL DEFAULT ""; +ALTER TABLE `talert_snmp` ADD COLUMN `al_field15` TEXT NOT NULL DEFAULT ""; +ALTER TABLE `talert_snmp` ADD COLUMN `al_field16` TEXT NOT NULL DEFAULT ""; +ALTER TABLE `talert_snmp` ADD COLUMN `al_field17` TEXT NOT NULL DEFAULT ""; +ALTER TABLE `talert_snmp` ADD COLUMN `al_field18` TEXT NOT NULL DEFAULT ""; +ALTER TABLE `talert_snmp` ADD COLUMN `al_field19` TEXT NOT NULL DEFAULT ""; +ALTER TABLE `talert_snmp` ADD COLUMN `al_field20` TEXT NOT NULL DEFAULT ""; ALTER TABLE `talert_snmp` ADD COLUMN `disable_event` tinyint(1) DEFAULT 0; ALTER TABLE `talert_snmp` MODIFY COLUMN `al_field11` text NOT NULL, MODIFY COLUMN `al_field12` text NOT NULL, @@ -1268,6 +1273,7 @@ ALTER TABLE `talert_snmp` MODIFY COLUMN `al_field11` text NOT NULL, MODIFY COLUMN `al_field14` text NOT NULL, MODIFY COLUMN `al_field15` text NOT NULL; + -- --------------------------------------------------------------------- -- Table `talert_snmp_action` -- --------------------------------------------------------------------- @@ -1405,6 +1411,7 @@ INSERT INTO `tconfig` (`token`, `value`) VALUES ('cr_incident_type', ''); INSERT INTO `tconfig` (`token`, `value`) VALUES ('cr_incident_status', ''); INSERT INTO `tconfig` (`token`, `value`) VALUES ('cr_incident_title', ''); INSERT INTO `tconfig` (`token`, `value`) VALUES ('cr_incident_content', ''); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('post_process_custom_values', '{"0.00000038580247":"Seconds to months","0.00000165343915":"Seconds to weeks","0.00001157407407":"Seconds to days","0.01666666666667":"Seconds to minutes","0.00000000093132":"Bytes to Gigabytes","0.00000095367432":"Bytes to Megabytes","0.00097656250000":"Bytes to Kilobytes","0.00000001653439":"Timeticks to weeks","0.00000011574074":"Timeticks to days"}'); -- --------------------------------------------------------------------- -- Table `tconfig_os` diff --git a/pandora_console/general/login_page.php b/pandora_console/general/login_page.php index c4cd8482bc..59257907ad 100755 --- a/pandora_console/general/login_page.php +++ b/pandora_console/general/login_page.php @@ -114,6 +114,13 @@ foreach ($custom_fields as $field) { } } +// Connection lost alert. +ui_require_css_file('register', 'include/styles/', true); +ui_require_javascript_file('connection_check'); +$conn_title = __('Connection with server has been lost'); +$conn_text = __('Connection to the server has been lost. Please check your internet connection or contact with administrator.'); +ui_print_message_dialog($conn_title, $conn_text, 'connection', '/images/error_1.png'); + // Get the custom icons. $docs_logo = ui_get_docs_logo(); $support_logo = ui_get_support_logo(); @@ -450,7 +457,12 @@ if ($login_screen == 'logout') { echo '
'; echo '
'; echo '

'.__('Logged out').'

'; - echo '

'.__('Your session has ended. Please close your browser window to close this %s session.', get_product_name()).'

'; + if (empty($config['logout_msg']) === true) { + echo '

'.__('Your session has ended. Please close your browser window to close this %s session.', get_product_name()).'

'; + } else { + echo '

'.__($config['logout_msg']).'

'; + } + echo '
'; echo '
'; html_print_submit_button('Ok', 'hide-login-logout', false); diff --git a/pandora_console/general/register.php b/pandora_console/general/register.php index e7097b994e..6d15c7ab2f 100644 --- a/pandora_console/general/register.php +++ b/pandora_console/general/register.php @@ -148,7 +148,8 @@ if ($initial && users_is_admin()) { config_wiz_modal( false, true, - (($registration === true) ? 'show_registration_wizard()' : null) + (($registration === true) ? 'show_registration_wizard()' : null), + true ); } @@ -159,7 +160,8 @@ if (!$config['disabled_newsletter']) { false, // Launch only if not being launch from 'initial'. !$initial, - (($show_newsletter === true) ? 'force_run_newsletter()' : null) + (($show_newsletter === false) ? 'force_run_newsletter()' : null), + true ); } else { if ($show_newsletter) { @@ -167,7 +169,8 @@ if (!$config['disabled_newsletter']) { newsletter_wiz_modal( false, // Launch only if not being call from 'registration'. - !$registration && !$initial + !$registration && !$initial, + true ); } } @@ -183,6 +186,88 @@ try { $welcome = false; } +$double_auth_enabled = (bool) db_get_value('id', 'tuser_double_auth', 'id_user', $config['id_user']); + +if (!$double_auth_enabled && $config['2FA_all_users'] != '' + && $config['2Fa_auth'] != '1' + && $config['double_auth_enabled'] +) { + echo '