Archive for linux

Persistencia com Cisco VPNc Client

O cliente de VPN da Cisco vpnc não mantém persistência na conexão, hora ou outra a conexão é finalizada. Para aqueles que precisam manter conexão 24×7 um script como estes será muito útil.

O script watch_vpnc possui 4 opções:

  • start: inicia a conexão
  • stop: finaliza a conexão
  • status: apenas verifica o status da conexão verificando se o arquivo PID existe E se existe o processo, pois pode ser que aconteça do daemon ser finalizado abruptamente (kill -9) e o arquivo ainda existir.
  • check: verifica se a conexão está ativa, se não estiver, reconecta.

Este script foi escrito com base no vpnc para RedHat/CentOS, para Ubuntu será necessário mudar a localização do arquivo PID.

Para manter como um “daemon” é recomendado rodá-lo na crontab, pois fazer um script com “sleep” não é uma boa idéia.

#!/usr/bin/env bash
# watchdog para Cisco vpnc Client
# v1, abril/2012 - ftorres[at]ymail.com
export PATH=$PATH/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
LOGFILE=/tmp/watch_vpn.log

Status()
{
        # Verifica se existe um processo com o mesmo numero do PID
        # Alguns casos podera existir o arquivo mas o daemon ter finalizado abruptamente.
        if [ -e /var/run/vpnc/pid ];then
                PID=$(cat /var/run/vpnc/pid)
                ps -p $PID -o comm= >/dev/null 2>&1
                RET=$?
                if [ $RET -eq 0 ];then
                        echo OK
                else
                        echo NOK
                fi
        else
                # Se o arquivo nem existir, nok
                echo NOK
        fi
}

Stop()
{
        pidof vpnc|xargs kill -15
        rm -f /var/run/vpnc/pid
}

Log_msg()
{
        echo "$(date '+%x - %X') $@"
}

Help()
{
        echo "$0 stop|start|status|check"
}

Vpn()
{
        if [ -f /tmp/watch.lock ];then
                Log_msg "Lock existe - /tmp/watch.lock"
                exit
        else
        > /tmp/watch.lock
        RET=$(Status)
        if [ "$RET" = "OK" ];then
                Log_msg "VPN OK"
                rm -f /tmp/watch.lock
        else
                Log_msg "VPN nao esta conectada"
                Stop
                vpnc
                rm -f /tmp/watch.lock
        fi
fi
}

Start()
{
        Stop
        Vpn
}

Check()
# Verifica o status da VPN, se nao estiver OK ele ira conectar.
{
        RET=$(Status)
        if [ "$RET" = "NOK" ];then
                Stop
                Start
        else
                echo $RET
                Log_msg $RET >> $LOGFILE

        fi

}

Main()
{
case "$1" in
        start) Start;;
        stop) Stop;;
        status) Status;;
        check) Check;;
        *) Help;;
esac
exit 0
}

[ -z "$1" ] &&  Help || Main $1

Se você precisa rodar a cada “segundo” e não quer construir um daemon e não quer usar “sleep”, então:

# Se quiser apenas a cada minuto
*/1 * * * * /usr/local/bin/watch_vpnc.sh check
# Se não estiver satisfeito e quiser apelar:
*/1 * * * * sleep 20 && /usr/local/bin/watch_vpnc.sh check
*/1 * * * * sleep 40 && /usr/local/bin/watch_vpnc.sh check

Transmission no Ubuntu

Instalando e configurando o transmission no seu ubuntu, pra mode baixar os torrents em casa e acessar um painel via web.

chupinhado do [email protected], o cara aqui do meu lado :)

A propósito, segue meu arquivo settings.json

{
    "alt-speed-down": 50,
    "alt-speed-enabled": false,
    "alt-speed-time-begin": 540,
    "alt-speed-time-day": 127,
    "alt-speed-time-enabled": false,
    "alt-speed-time-end": 1020,
    "alt-speed-up": 50,
    "bind-address-ipv4": "0.0.0.0",
    "bind-address-ipv6": "::",
    "blocklist-enabled": false,
    "blocklist-url": "http://www.example.com/blocklist",
    "cache-size-mb": 4,
    "dht-enabled": true,
    "download-dir": "/home/ftorres/Downloads/transmission",
    "download-limit": 100,
    "download-limit-enabled": 0,
    "encryption": 1,
    "idle-seeding-limit": 30,
    "idle-seeding-limit-enabled": false,
    "incomplete-dir": "/home/ftorres/Downloads/transmission/.incomplete",
    "incomplete-dir-enabled": true,
    "lpd-enabled": false,
    "max-peers-global": 200,
    "message-level": 2,
    "open-file-limit": 32,
    "peer-congestion-algorithm": "",
    "peer-limit-global": 240,
    "peer-limit-per-torrent": 60,
    "peer-port": 51413,
    "peer-port-random-high": 65535,
    "peer-port-random-low": 49152,
    "peer-port-random-on-start": false,
    "peer-socket-tos": "default",
    "pex-enabled": true,
    "port-forwarding-enabled": false,
    "preallocation": 1,
    "prefetch-enabled": 1,
    "ratio-limit": 2,
    "ratio-limit-enabled": false,
    "rename-partial-files": true,
    "rpc-authentication-required": true,
    "rpc-bind-address": "0.0.0.0",
    "rpc-enabled": true,
    "rpc-password": "SUASENHA:depois_ele_encriptará",
    "rpc-port": 9091,
    "rpc-url": "/transmission/",
    "rpc-username": "SEU_USUARIO",
    "rpc-whitelist": "127.0.0.1",
    "rpc-whitelist-enabled": false,
    "script-torrent-done-enabled": false,
    "script-torrent-done-filename": "",
    "speed-limit-down": 100,
    "speed-limit-down-enabled": false,
    "speed-limit-up": 10,
    "speed-limit-up-enabled": true,
    "start-added-torrents": true,
    "trash-original-torrent-files": false,
    "umask": 18,
    "upload-limit": 100,
    "upload-limit-enabled": 0,
    "upload-slots-per-torrent": 14,
    "utp-enabled": true
} 

Crie e dê permissão no diretório que irá salvar os arquivos:

mkdir -p /home/ftorres/Downloads/transmission/.incomplete && chown debian-transmission. /home/ftorres/Downloads/transmission -R

Inicie o daemon do transmission e acesse via web, porta 9091.

Não esqueça de liberar a porta do transmission no seu firewall/port forwarding.

Troubleshooting:

Transmission “morre” com segment fault:

Apr 10 16:48:12 bazzinga kernel: [31339.039702] transmission-da[13355]: segfault at 3c ip 0805fa42 sp b6f88e30 error 4 in transmission-daemon[8048000+6e000]

Solução:

Adicionar a linha no arquivo settings.json

 "open-file-limit": 32,

ActiveMQ 5 com persistência JDBC em Oracle

Configurando o apache activemq 5.5.1 com persistência JDBC no Oracle 11g

Você precisará configurar, corretamente, apenas 2 arquivos:

  • activemq.xml
  • activemq-jdbc.xml
  • camel.xml

O camel.xml será utilizado apenas para o jmsloader, usado no stress test do activemq que iremos fazer ;)

Primeiro, baixe o driver oracle jdbc, ojdbc6.jar e armazene ele dentro de activemq/lib/optional

Arquivo activemq.xml

Adicionado a linha: 25, importando o arquivo camel.xml (ele será usado para jmsloader)
Comentei o bloco iniciado na linha: 50, destinationPolicy. Note que a linha 60 também leva um comentário, pois no xml um comentário dentro de comentário vai dar zica.
Configurei a linha: 93, jdbcPersistenceAdapter, vital para o conector persistente jdbc.
Adicionado as linhas: 129 130 e 131, amq:connectionFactory, para testes com o jmsloader)
Adicionado a linha: 139, o

<!--
    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
    this work for additional information regarding copyright ownership.
    The ASF licenses this file to You under the Apache License, Version 2.0
    (the "License"); you may not use this file except in compliance with
    the License.  You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
-->
<!-- START SNIPPET: example -->
<beans
  xmlns="http://www.springframework.org/schema/beans"
  xmlns:amq="http://activemq.apache.org/schema/core"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
  http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd">

<import resource="camel.xml"/>

    <!-- Allows us to use system properties as variables in this configuration file -->
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <value>file:${activemq.base}/conf/credentials.properties</value>
        </property>
    </bean>

    <!--
        The <broker> element is used to configure the ActiveMQ broker.
    -->
    <broker xmlns="http://activemq.apache.org/schema/core" brokerName="localhost" dataDirectory="${activemq.base}/data" destroyApplicationContextOnStop="true">

        <!--
                        For better performances use VM cursor and small memory limit.
                        For more information, see:

http://activemq.apache.org/message-cursors.html

            Also, if your producer is "hanging", it's probably due to producer flow control.
            For more information, see:

http://activemq.apache.org/producer-flow-control.html

        -->

        <!--
        <destinationPolicy>
            <policyMap>
              <policyEntries>
                <policyEntry topic=">" producerFlowControl="true" memoryLimit="1mb">
                  <pendingSubscriberPolicy>
                    <vmCursor />
                  </pendingSubscriberPolicy>
                </policyEntry>
                <policyEntry queue=">" producerFlowControl="true" memoryLimit="1mb">
                  ##<!- Use VM cursor for better latency
                       For more information, see:

http://activemq.apache.org/message-cursors.html

                  <pendingQueuePolicy>
                    <vmQueueCursor/>
                  </pendingQueuePolicy>
                  ##->
                </policyEntry>
              </policyEntries>
            </policyMap>
        </destinationPolicy>
         -->

        <!--
            The managementContext is used to configure how ActiveMQ is exposed in
            JMX. By default, ActiveMQ uses the MBean server that is started by
            the JVM. For more information, see: 

http://activemq.apache.org/jmx.html

        -->
        <managementContext>
            <managementContext createConnector="false"/>
        </managementContext>

        <!--
            Configure message persistence for the broker. The default persistence
            mechanism is the KahaDB store (identified by the kahaDB tag).
            For more information, see: 

http://activemq.apache.org/persistence.html

        -->
        <persistenceAdapter>
              <jdbcPersistenceAdapter dataSource="#oracle-ds"/>
        </persistenceAdapter>
          <!--
            The systemUsage controls the maximum amount of space the broker will
            use before slowing down producers. For more information, see:

http://activemq.apache.org/producer-flow-control.html

        <systemUsage>
            <systemUsage>
                <memoryUsage>
                    <memoryUsage limit="20 mb"/>
                </memoryUsage>
                <storeUsage>
                    <storeUsage limit="1 gb"/>
                </storeUsage>
                <tempUsage>
                    <tempUsage limit="100 mb"/>
                </tempUsage>
            </systemUsage>
        </systemUsage>
                -->

        <!--
            The transport connectors expose ActiveMQ over a given protocol to
            clients and other brokers. For more information, see: 

http://activemq.apache.org/configuring-transports.html

        -->
        <transportConnectors>
            <transportConnector name="openwire" uri="tcp://0.0.0.0:61616"/>
        </transportConnectors>

    </broker>

        <amq:connectionFactory brokerURL="tcp://0.0.0.0:61616" id="ConnectionFactory" />
        <amq:queue id="exampleA" name="example.A" physicalName="example.A" />
        <amq:queue id="exampleB" name="example.B" physicalName="example.B" />

    <!--
        Enable web consoles, REST and Ajax APIs and demos

        Take a look at ${ACTIVEMQ_HOME}/conf/jetty.xml for more details
    -->
    <import resource="jetty.xml"/>
    <import resource="activemq-jdbc.xml"/>

</beans>
<!--END SNIPPET: example -->

Arquivo activemq-jdbc.xml

alterei as linha: 45, adicionando o novo dataSource oracle-ds
comentei a linha: 49, transportConnectors, pois ele já está definido no arquivo activemq.xml
comentei a linha: 54, o bean derby-ds, pois vamos utilizar o Oracle
configurei o bloco da linha: 88, adicionado configurações do Oracle DataSource

<!--
    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
    this work for additional information regarding copyright ownership.
    The ASF licenses this file to You under the Apache License, Version 2.0
    (the "License"); you may not use this file except in compliance with
    the License.  You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
-->
<!--
    Use JDBC for message persistence
    For more information, see:

http://activemq.apache.org/persistence.html

    You need to add Derby database to your classpath in order to make this example work.
    Download it from http://db.apache.org/derby/ and put it in the ${ACTIVEMQ_HOME}/lib/optional/ folder
    Optionally you can configure any other RDBM as shown below

    To run ActiveMQ with this configuration add xbean:conf/activemq-jdbc.xml to your command

    e.g. $ bin/activemq console xbean:conf/activemq-jdbc.xml
 -->
<beans
  xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
  http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd">

  <!-- Allows us to use system properties as variables in this configuration file -->
  <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
      <property name="locations">
          <value>file:${activemq.base}/conf/credentials.properties</value>
      </property>
  </bean>

  <broker useJmx="false" brokerName="jdbcBroker" xmlns="http://activemq.apache.org/schema/core">
    <persistenceAdapter>
       <jdbcPersistenceAdapter dataDirectory="${activemq.base}/data" dataSource="#oracle-ds"/>
    </persistenceAdapter>

    <!-- transportConnectors>
       <transportConnector name="default" uri="tcp://0.0.0.0:61616"/>
    </transportConnectors -->
  </broker>

  <!-- Embedded Derby DataSource Sample Setup
  <bean id="derby-ds" class="org.apache.derby.jdbc.EmbeddedDataSource">
    <property name="databaseName" value="derbydb"/>
    <property name="createDatabase" value="create"/>
  </bean> -->

  <!-- Postgres DataSource Sample Setup -->
  <!--
  <bean id="postgres-ds" class="org.postgresql.ds.PGPoolingDataSource">
    <property name="serverName" value="localhost"/>
    <property name="databaseName" value="activemq"/>
    <property name="portNumber" value="0"/>
    <property name="user" value="activemq"/>
    <property name="password" value="activemq"/>
    <property name="dataSourceName" value="postgres"/>
    <property name="initialConnections" value="1"/>
    <property name="maxConnections" value="10"/>
  </bean>
  -->

  <!-- MySql DataSource Sample Setup -->
  <!--
  <bean id="mysql-ds" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost/activemq?relaxAutoCommit=true"/>
    <property name="username" value="activemq"/>
    <property name="password" value="activemq"/>
    <property name="maxActive" value="200"/>
    <property name="poolPreparedStatements" value="true"/>
  </bean>
  -->

  <!-- Oracle DataSource Sample Setup -->

  <bean id="oracle-ds" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
    <property name="url" value="jdbc:oracle:thin:@HOST:1521:DBNAME"/>
    <property name="username" value="USERNAME"/>
    <property name="password" value="PASSWD"/>
    <property name="maxActive" value="200"/>
    <property name="poolPreparedStatements" value="true"/>
  </bean>

</beans>

Arquivo camel.xml
Configurado as rotas de fila para o Camel.

 <!--
    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
    this work for additional information regarding copyright ownership.
    The ASF licenses this file to You under the Apache License, Version 2.0
    (the "License"); you may not use this file except in compliance with
    the License.  You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
-->
<!--

    Lets deploy some Enterprise Integration Patterns inside the ActiveMQ Message Broker
    For more information, see:

http://camel.apache.org

    Include this file in your configuration to enable Camel

    e.g. <import resource="camel.xml"/>

-->
<beans
   xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd
   http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

        <camelContext id="camel" xmlns="http://camel.apache.org/schema/spring">

        <!-- You can use a <packages> element for each root package to search for Java routes -->
        <packageScan>
           <package>org.foo.bar</package>
        </packageScan>

        <!-- You can use Spring XML syntax to define the routes here using the <route> element -->
        <route>
            <description>Example Camel Route</description>
            <from uri="activemq:example.A"/>
            <!-- to uri="activemq:example.B"/ -->
            <inOnly uri="activemq:example.B"/>
        </route>
    </camelContext>

    <!--
       Lets configure some Camel endpoints

http://camel.apache.org/components.html

    -->

    <!-- configure the camel activemq component to use the current broker -->
    <bean id="activemq" class="org.apache.activemq.camel.component.ActiveMQComponent" >
        <property name="connectionFactory">
          <bean class="org.apache.activemq.ActiveMQConnectionFactory">
            <!-- property name="brokerURL" value="vm://localhost?create=false&amp;waitForStart=10000" / -->
            <property name="brokerURL" value="tcp://localhost:61616" />
            <property name="userName" value="${activemq.username}"/>
            <property name="password" value="${activemq.password}"/>
          </bean>
        </property>
    </bean>
</beans>

Mais sobre a Arquitetura ActiveMQ: http://activemq.apache.org/jdbc-master-slave.html

Resetar senha root do MySQL

Da série: Pouco usado e pouco lembrado.

Para resetar a senha do mysql, proceda como abaixo:

1) Finalize o daemon mysqld

/etc/init.d/mysqld stop

2) Após finalizado, execute:

mysqld_safe --skip-grant-tables &

3) Conecte no mysql como root e sem senha e execute os comandos:

 mysql -uroot -p
mysql> UPDATE mysql.user SET Password=PASSWORD('SENHA') WHERE User='root'
mysql> flush privileges
mysql> quit

Agora, finalize o mysqld_safe iniciado anteriormente:

ps -efwww|grep mysql|awk '{print $1}' |xargs kill -15

Agora, para finalizar, inicie o mysql no modo convencional e conecte com a nova senha:

/etc/init.d/mysqld start

Node.js para administradores de sistema

Não irei migrar este artigo para o wordpress, mas ele pode ser acessado no antigo endereço: http://flaviotorres.com.br/fnt/artigos/node_js.php

Gerando estatisticas do seu DNS com o zabbix

Não irei migrar este artigo para o wordpress, mas ele pode ser acessado no endereço original: http://flaviotorres.com.br/fnt/artigos/zabbix_bind_named.php

Business Intelligence – Pentaho 3.5 com PostgreSQL

Não irei migrar este artigo para o wordpress, mas ele pode ser acessado pelo antigo endereço: http://flaviotorres.com.br/fnt/artigos/pentaho_35_postgresql.php