Commands for openindiana

Openindiana

dladm show-phys # to see interface configured datalink , interface speed

To view information on array status and disk pool
zpool status -v
https://docs.oracle.com/cd/E19253-01/819-5461/gamno/index.html

zabbix all-shutdown

Shutdown all hosts connected to a ups with low charge

Create a host related to the UPS

Create a trigger related to the ups_charge with the name “ups_charge”

Example problem expression

{Zabbix server:ups_charge.max(5m)}<60 and {Zabbix server:ups_charge.max(5m)}>0

Configuration -> Actions

Create a Action

Name: ups_charge_action

Add a new condition

Trigger name contains “ups_charge” (name of the trigger)

In Operations

Add a new operational detail

Target List: (Linux Servers or other target)
Operational Type: Remote command
type: custom script
Execute on: Zabbix Agent
commands: sudo /sbin/shutdown -h now

Other commands , for windows shutdown

c:\windows\system32\shutdown.exe /s /f

Conditions
Event Acknowledge equal not ack

Recovery Operations

Operation type: Remote Command
Target List: (Linux Servers or other target)
Type: Custom script
Execute on: zabbix agent
Commands: sudo /sbin/shutdown -c

Press “Add”

On the hosts Agents

execute visudo and add

zabbix ALL=(ALL:ALL) NOPASSWD:/sbin/shutdown

edit /etc/zabbix/zabbix_agentd.conf and enable
EnableRemoteCommand=1

Make sure the agent is enabled on boot
systemctl enable zabbix-agent

Restart the agent
sudo /etc/init.d/zabbix-agent restart

Zabbix Debian Install

Install instructions:
https://www.zabbix.com/documentation/4.0/manual/installation/install_from_packages/debian_ubuntu

# apt install zabbix-server-mysql

# apt install zabbix-frontend-php

# mysql
create database zabbix character set utf8 collate utf8_bin;

grant all on zabbix.* to zabbix identified by ‘awsome password’;

flush privileges;

zcat /usr/share/doc/zabbix-server-mysql/create.sql.gz | mysql -uzabbix -p zabbix

# vi /etc/zabbix/zabbix_server.conf

https://www.zabbix.com/documentation/4.0/manual/installation/install#installing_frontend

# openssl rand -hex 512

Increase CacheSize zabbix_server.conf
CacheSize=32M

rSyslog

Guardar dados em queue no rsyslog client

Guardar dados em queue no rsyslog client caso não consiga contactar o rsyslog server

# start forwarding rule 1
$ActionQueueType LinkedList # use asynchronous processing
$ActionQueueFileName srvrfwd1 # set file name, also enables disk mode
$ActionResumeRetryCount -1 # infinite retries on insert failure
$ActionQueueSaveOnShutdown on # save in-memory data if rsyslog shuts down
*.* @@server1:port
# end forwarding rule 1
#
https://www.rsyslog.com/doc/v8-stable/tutorials/reliable_forwarding.html

rSyslog servidor

Guardar logs com nome de hostname cliente

No /etc/rsyslog.d/ criar um arquivo “59-remotehostname-in-file.conf” com a configuração abaixo

$template DynaFile,”/var/log/system-%HOSTNAME%.log”
*.* -?DynaFile

 

 

Grafana snmp_exporter auth reusage issue

FROM: https://github.com/prometheus/snmp_exporter/issues/221

For when in snmp_exporter you want to use a existing module but implement a different authentication method to a new device or group of devices.

It occurs to me that there is another approach: merging YAML references using the << merge key (spec).

This is an optional part of YAML so I don’t know if the go YAML parser supports it.

It looks something like this:

apcups: &apcups
  walk:
  - 1.3.6.1.2.1.1.3
  - etc
apcups_london:
  <<: *apcups
  version: 2
  auth:
    community: blah

Using Python’s yaml parser I get:

>>> x = yaml.load(open("/home/brian/tmp.yml"))
>>> x
{'apcups_london': {'version': 2, 'auth': {'community': 'blah'}, 'walk': ['1.3.6.1.2.1.1.3', 'etc']}, 'apcups': {'walk': ['1.3.6.1.2.1.1.3', 'etc']}}

Conveniently, the references point to the same underlying object, so the storage is shared.

>>> id(x['apcups_london']['walk'])
140041579271160
>>> id(x['apcups']['walk'])
140041579271160

Docker php:7.2-fpm and openssl extension

While running the installation of php 7.2 fpm of docker I ran into the issue caused by the installation of the extension openssl. Using docker-php-ext-install openssl resulted in a error config.m4 not found , I thought there would be a easy way to solve this but no.
I had to create a script based on docker-php-ext-install to just install the openssl extension by moving the mv config0.m4 to config.m4

https://stackoverflow.com/questions/43881834/php-openssl-in-ubuntu

 

In the Dockerfile where I’m building From php:7.2-ppm

COPY openssl.sh /
RUN chmod 0750 /openssl.sh && cd / && ./openssl.sh

In the openssl.sh file

#!/bin/bash

#!/bin/sh
set -e

# prefer user supplied CFLAGS, but default to our PHP_CFLAGS
: ${CFLAGS:=$PHP_CFLAGS}
: ${CPPFLAGS:=$PHP_CPPFLAGS}
: ${LDFLAGS:=$PHP_LDFLAGS}
export CFLAGS CPPFLAGS LDFLAGS

srcExists=
if [ -d /usr/src/php ]; then
srcExists=1
fi
docker-php-source extract
if [ -z “$srcExists” ]; then
touch /usr/src/php/.docker-delete-me
fi

cd /usr/src/php/ext

pm=’unknown’
if [ -e /lib/apk/db/installed ]; then
pm=’apk’
fi

apkDel=
if [ “$pm” = ‘apk’ ]; then
if [ -n “$PHPIZE_DEPS” ]; then
if apk info –installed .phpize-deps-configure > /dev/null; then
apkDel=’.phpize-deps-configure’
elif ! apk info –installed .phpize-deps > /dev/null; then
apk add –no-cache –virtual .phpize-deps $PHPIZE_DEPS
apkDel=’.phpize-deps’
fi
fi
fi

popDir=”$PWD”
cd openssl
mv config0.m4 config.m4
[ -e Makefile ] || docker-php-ext-configure openssl
make
make install
find modules \
-maxdepth 1 \
-name ‘*.so’ \
-exec basename ‘{}’ ‘;’ \
| xargs -r docker-php-ext-enable
make clean
cd “$popDir”

if [ “$pm” = ‘apk’ ] && [ -n “$apkDel” ]; then
apk del $apkDel
fi

if [ -e /usr/src/php/.docker-delete-me ]; then
docker-php-source delete
fi

 

PHP Taking advantage of Traits and Doctrine2 for less lines of code

I did this app a time ago (~1 year) with Doctrine2+Symfony2 with simple Entities basically I was mimicking an excel sheet copying the values from the sheet to the database and setting all up for web usage.

The main Class was Item, this had Sub Entities Location, Protocol, State, etc…

These named here Location, Protocol, State had the same properties (fields), they also had to have a incrementable “Code” field witch, this was a basic copy paste to fill the tables and increment the number. Didn’t want to write the code to the different Entities so I used a Trait in a very lazy way I declared

TautoFill

namespace Far\AssetManagerBundle\Entity;

trait TautoFill {

    public function getAndInsert($val)
    {
        $this->_em->getConnection()->beginTransaction();

        $valtmp = strtoupper(str_replace(' ','',trim($val)));
        $Res = $this->findBy(['code' => $valtmp]);
        if (count($Res) > 0 && $Res[0] != null) {
            $obj = $Res[0];
            $obj->setTcount($obj->getTcount()+1);
            $this->_em->persist($obj);

            $this->_em->flush();

        } else {
            $tmp = $this->getClassName();
            $obj = new $tmp();
            $obj->setDescription($val);
            $obj->setCode($valtmp);
            $obj->setTcount(1);
            // persist
            $this->_em->persist($obj);
            $this->_em->flush();
        }

        $this->_em->getConnection()->commit();
        return $obj;
    }
}

So in a easy use TautoFill I got the data auto inserted and related to the main Item, without much work. Using a trait made the code more dynamic and easier to reimplement in the different situations without compromising hierarchy of the Entities.

Mysql e output de erros

Engraçado tive um problema parecido mesma mensagem de erro e não tinha nada a ver com a Base de dados o problema é na config do servidor… Foda-se!

Re: ERROR 1033 (HY000): Incorrect information in file
Posted by: Stu Derby ()
Date: October 28, 2007 02:14PM

As best I can tell, this error message is produced whenever the DB is unable to perform INNODB recovery upon restart. The DB needs to assume on restart that it might have crashed, maybe power failure, and so there may be partially stored transactions in the log file that either need to be completed or unwound. If it can’t do that, recovery fails and the tables are therefore inaccessible, with this rather cryptic message.

I ran into this problem when restoring a slave DB, using the backup of the master. Someone had cleverly (not) increased the innodb_log_file_size on the slave but not the master and I was using the master’s data and log files with the slave’s my.cnf The only clues I got were the 1033 error message and the startup error message (in /var/log/mysqld.log on my system):
InnoDB: Error: log file /var/lib/mysql/ib_logfile0 is of different size 0 268435456 bytes
InnoDB: than specified in the .cnf file 0 536870912 bytes!

Making the slave’s log_file_size match the log file copied from the master made everything work (some 12 hours after I started on the problem).

I suspect there are several other ways to get this situation, probably corrupted or missing log files, path problems, etc. It would be nice if the DB would put out an error saying something like “recovery has failed, InnoDB tables not accessible” to help people focus on the earlier error (in my case the log file size issue).

Controlo de uso de CPU em perl

Fica aqui o codigo que escrevi simples mas modular o suficiente para ser replicado por mais pessoas.

GPLv2

Desculpem a mistura de Inglês com o Português.


#
# Verificar o tempo de idle do cpu e agir de acordo
#
# @version $Id: idletime.pm 5432 2011-05-05
#
#

# Permitir um tempo maximo de idle de x segundos
# Definir o tempo permitido em idle por esta var
#
our $processcount_cpuallowidletime = 120;
# Maximo de tempo que o processo ira ficar com controlo de idle time
our $processcount_cpuallowtotalidletime = 500;

# dormir durante x tempo porque o processo esteve sem fazer nada
our $process_sleeptime = 2;

#
# Guardar dados sobre idle process count
#
# Estrutura de dados para indicar o tempo de idletime
#
our %idletime = (
start => 0,
end => 0,
total => 0,
);

# $processcount pertence ao ficheiro "main" e nao deve ser definido aqui
# esta var indica se o processo esta a fazer algo se > 0

=item checkidle

Called function to validate idle time

=cut

sub checkidle {
if ($DEBUG > 0 ) {
syslog("debug", "inicio Verificar idle time pcount=".$processcount." t=".$idletime{'total'}." allow=".$processcount_cpuallowidletime." pslp=".$process_sleeptime);
}

if ($processcount == 0 ) {

if ( $idletime{'start'} == 0 ) {
$idletime{'start'} = time();
}

$idletime{'end'} = time();

$idletime{'total'} = $idletime{'end'} - $idletime{'start'};

}

if ($idletime{'total'} > $processcount_cpuallowidletime ) {
$process_sleeptime = $process_sleeptime*2; # recalculate value of sleep time
if ($DEBUG > 0 ) {
syslog("debug", "A dormir durante ".$process_sleeptime." seconds...");
}
syslog("info", "Sleeping:".$process_sleeptime);
sleep($process_sleeptime);
}

if ( ($processcount > 0 || $idletime{'total'} > $processcount_cpuallowtotalidletime) && $idletime{'start'} != 0 ) {
resetIdleTime();
}

if ( $DEBUG > 0 ) {
syslog("debug", "fim Verificar idle time ".$processcount." ".$idletime{'total'}." ".$processcount_cpuallowidletime);
}

if ($process_sleeptime > $processcount_cpuallowtotalidletime ) {
$process_sleeptime = 1;
}
}

=item resetIdleTime()

Reset idle time counters

=cut

sub resetIdleTime {
$idletime{'start'} = 0;
$idletime{'end'} = 0;
$idletime{'total'} = 0;
}

1;

GSM Decryption Published

“The NY Times reports that German encryption expert Karsten Nohl says that he has deciphered and published the 21-year-old GSM algorithm, the secret code used to encrypt most of the world’s digital mobile phone calls, in what he called an attempt to expose weaknesses in the security system used by about 3.5 billion of the 4.3 billion wireless connections across the globe. Others have cracked the A5/1 encryption technology used in GSM before, but their results have remained secret. ‘This shows that existing GSM security is inadequate,’ Nohl told about 600 people attending the Chaos Communication Congress. ‘We are trying to push operators to adopt better security measures for mobile phone calls.’ The GSM Association, the industry group based in London that devised the algorithm and represents wireless operators, called Mr. Nohl’s efforts illegal and said they overstated the security threat to wireless calls. ‘This is theoretically possible but practically unlikely,’ says Claire Cranton, a GSM spokeswoman, noting that no one else had broken the code since its adoption. ‘What he is doing would be illegal in Britain and the United States. To do this while supposedly being concerned about privacy is beyond me.’ Simon Bransfield-Garth, the chief executive of Cellcrypt, says Nohl’s efforts could put sophisticated mobile interception technology — limited to governments and intelligence agencies — within the reach of any reasonable well-funded criminal organization. ‘This will reduce the time to break a GSM call from weeks to hours,’ Bransfield-Garth says. ‘We expect as this further develops it will be reduced to minutes.'”

Esta conversa sobre ser ilegal quebrar o algoritmo GSM lembrou-me a conversa de Rob Savoye sobre o facto de não poder fazer Reverse Enginering aplicando “atalhos” e por isso demorar mais tempo a conseguir resultados. Mas no final tal como Nohl conseguiu desencriptar o GSM outros também o conseguirão é apenas preciso tempo e paciência.
A única preocupação de certas pessoas é que as falhas das quais certos governos(US) e organizações(NSA) se aproveitam lhes fujam ao controlo.