Às vezes eu escrevo programas. Entre esse programas, alguns são daemons.
Além da confusão com demônios, o que são daemons?
Daemons são os programas que rodam em background no sistema, não precisando de um terminal (console) anexado. E qualquer tipo de programa pode ser um daemon, pra qualquer finalidade.
Em geral daemons seguem as seguintes regras pra se tornarem daemons:
O segundo fork() é feito para garantir que o programa, através do segundo processo filho, seja "herdado" pelo processo init do sistema.
Em Python, sempre incluo uma função como essa:
def Daemonize(self):
"""
Fork to became a daemon.
"""
if not self.isDaemon:
try:
self.run()
except KeyboardInterrupt:
sys.exit(0)
return
os.chdir("/")
pid = os.fork()
if (pid > 0):
sys.exit(os.EX_OK)
else:
pid = os.fork()
if (pid > 0):
sys.exit(os.EX_OK)
else:
self.run()
Esse é parte de um método, mas poderia ser uma função. A idéia é usar o getopt() para verificar as opções passadas e entrar no modo de daemon ou não, dependendo da opção passada, que modifica a variável booleana self.isDaemon.
Mas um dos meus programs começou a apresentar o seguinte erro:
helio@goosfraba:~$ connect_TSP.py ccn
IP already setup... skipping root access
Running as daemon
daemonized...
close failed in file object destructor:
IOError: [Errno 10] No child processes
Error in sys.excepthook:
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/apport_python_hook.py", line 66, in apport_excepthook
from apport.fileutils import likely_packaged, get_recent_crashes
RuntimeError: sys.meta_path must be a list of import hooks
Original exception was:
IOError: [Errno 10] No child processes
Inicialmente achei que era problema no "apport" com meu programa, que usa python-expect. Mesmo com tal erro, o programa funcionava perfeitamente em background, como daemon. Várias fontes na Internet, principalmente no Launchpad, o sistema de bug report do Ubuntu, várias pessoas reclamavam de tal erro como sendo problema do apport.
Após muito buscar a origem do problema, não no Ubuntu, mas no python, descobri que alguns file descriptors estavam causando esse erro, por continuarem abertos quando ocorria o fork(). Corrigi da seguinte forma:
def Daemonize(self):
"""
Fork to became a daemon.
"""
if not self.isDaemon:
try:
self.run()
except KeyboardInterrupt:
sys.exit(0)
return
os.chdir("/")
pid = os.fork()
if (pid > 0):
os.close(sys.stdin.fileno())
os.close(sys.stout.fileno())
os.close(sys.stderr.fileno())
sys.exit(os.EX_OK)
else:
pid = os.fork()
if (pid > 0):
os.close(sys.stdin.fileno())
os.close(sys.stdout.fileno())
os.close(sys.stderr.fileno())
sys.exit(os.EX_OK)
else:
self.run()
então bastou fechar os descritores de arquivo do STDIN, STDOU e STDERR pra ter certeza que o daemon não sairia com o erro acima.
Happy hacking :-)
Acaba de ser publicada a edição número 52 da revista Espírito Livre. Uma edição totalmente dedicada ao FISL 14 e... com um artigo meu!!!
Nada muito estravagante, apenas uma descrição de como foi o FISL para mim. E com as fotos que tirei durante todo o evento.
Infelizmente o servidor da revista Espírito Livre parece estar sofrendo o tráfego intenso, então está bastante difícil acessar a revista e baixar. Mas aos que conseguirem (e com certeza uma hora ou outra conseguirão), espero que gostem.
Esse enviei 2 apresentações pra Python Brasil. Uma falando sobre python-twitter (e como faço pra enviar os #FF de sexta-feira) e outra pra falar sobre python em telecomunicações.
Não tenho nada escrito ainda, e vou aguardar a confirmação do trabalho pra começar. Se der certo, estarei em Brasília no início de outubro :-)
Finalmente resolvi adicionar meu próprio PPA, Personal Package Archive - ou Arquivo de pacote pessoal, no Launchpad do Ubuntu. Isso vai me permitir distribuir facilmente os pacotes que crio. São para uso meu, baseado num Ubuntu LTS 12.04, mas podem ajudar mais pessoas.
Pra começar, fiz um upload do backport do python-twitter 1.0.1, que funciona com a API v1.1.
Para quem desejar usar meu repositório, deve bastar adicionar o PPA.
sudo add-apt-repository ppa:helioloureiro |
Minha chave PGP ainda não foi adicionada, mas isso deve ser corrigido em algum commit do sistema, o que talvez demore 1 dia. Até lá, meu pacote python-twitter não aparecerá como disponível.
Meu próximo upload deve ser dos pf-kernel. Já tenho compilado as versões 3.9.5 e 3.10.0.
Mais uma vez consegui peregrinar e me juntar ao grupo de ativistas e programadores que se reúnem uma vez ao ano em Porto Alegre, RS, para o FISL, Fórum Internacional de Software Livre.
Como sempre, foi um evento agradável e cheio de reencontros. Amigos que não via a mais de 10 anos!
Esse ano escolhi uma participação um pouco mais ativa, e fiz 2 oficinas de criação de pacotes. Na verdade a idéia era fazer uma iniciação na criação de pacotes durante a primeira oficina, e continuar com uma hackaton na segunda, mas o público da segunda oficina foi... completamente diferente da primeira! Devo supor que a primeira oficina foi um completo desastre e as pessoas desistiram de vez de fazer pacotes. E tive de re-fazer a parte didática durante a segunda, o que não permitiu corrigir nenhuma pacote oficial. Mas não deixou de ser divertido (ao menos para mim).
Além do encontro especial com os amigos, tive o prazer de participar de um churrasco numa cervejaria artesanal. Helles, ipa, weiss, red ale, pilsen... realmente um evento que deu um *gostinho* a mais ao FISL. E que gostinho bom.
Não bastasse o sabor ímpar das cervejas, descobri que quem tinha organizado a festança era a caravana de Florianópolis, da UFSC! Foi um encontro etílico do "old school" com o "new school". E tinha até o Maddog por lá.
Enfim o FISL foi mais uma vez um espetáculo. Espero ter condições para poder estar por lá no ano que vem novamente.
Não fiz muita propaganda por aqui (e devia ter feito), mas participei do FISL 14, em Porto Alegre, RS, com uma oficina de criação de pacotes DEB. Tentei criar uma sinergia de Debian com Ubuntu, sem focar em nenhum dos dois, e mostrando com pacotes pode ser criados para ambos.
Aqui está a apresentação, em prezi, que usei durante o evento.
Finalmente chegou o momento em que me rendi novamente ao appeal corporativo e voltei a utilizar um equipamento da empresa, e não mais um laptop meu e pessoal.
Optei por um equipamento que fosse homologado internamente para rodar Linux, e então recebi um considerado "high end laptop": um notebook HP EliteBook 8570w.
A instalação foi bem tranquila. Bastou inserir o pendrive e seguir com os passos de instalação do Ubuntu via rede.
Sem mexer em nada, o sistema já saiu funcionando: webcam, wifi, som, etc. A única coisa que ficou faltando, mas que foi corretamente notificada pelo Ubuntu, foi a placa de vídeo nvidia, e para instalar os drivers proprietários. E que bela placa de vídeo: NVIDIA GPU Quadro K1000M (GK107GL) com 2 GB de memória dedicada. Alguns sites não recomendam essa placa para jogos, mas com certeza esse não é o meu objetivo com esse equipamento.
Mas vamos ver um pouco mais do hardware:
Ainda tem uma porção de coisas que não consegui identificar. Existe no hardware, mas não vejo nas saídas de lspci e lsusb, ou mesmo lshw. Um bom exemplo é uma porta de modem que tem na parte de trás do laptop.
Minha primeira impressão sobre o laptop é... ele é um monstrobook. É enorme e pesado. Pesa 3 Kg pela descrição técnica, mas parece que são uns 15 Kg. É um hardware grande e confortável para digitar, mas tão grande que tem até teclado numérico junto. E deixa isso claro pela informação na traseira, onde se descreve como "Workstation", não um notebook ou laptop. Para quem estava acostumado com um laptop fofucho de 13 polegadas, é uma mudança muito grande.
Tem ainda uma série de botões para uso ou do touchpad ou do pointer que fica no meio do teclado, algo desnecessário. As teclas são confortáveis, mas poderia ter ao menos iluminação.
Os botões para habilitar/desabilitar wireless e som, que ficam no topo à direita, funcionam sem problemas. Os outros dois botões que ficam por lá também, para acesso rápido à Internet e para uma... calculadora? Esses não funcionam para nada. O de acesso à Internet dá um refresh na página web que se está lendo.
Sobre o botão de bloqueio de som, esse não funcionou _exatamente_ de primeira. Ele mostrava o bloqueio do som, mas sem efeito concreto disso. O motivo foi que pulseaudio apontava pra saída do DisplayPort como principal. Bastou utilizar o aplicativo pavucontrol e modificar o padrão pra saída de som normal que o botão funcionou corretamente.
O site da HP dá bastantes detalhes sobre o equipamento e seu uso em potencial.
o que chama a atenção é que esse é um hardware certificado para usar Linux. Acho que nunca tinha usado um laptop que tivesse isso. Não é certificado para Ubuntu, mas se funcionou com uma distribuição de Linux, funciona com todas.
E a HP chegou mesmo a fazer até um vídeo sobre o laptop. (vídeo foi removido)
É um equipamento legal, parrudo, mas pesado. O carcaça é de aço escovado, o que dá um certo charme ao conjunto. Faz falta também uma saída HDMI ao invés de DisplayPort. E a autonomia da bateria é baixa, entre 2 e 3 horas apenas. Estou gostando dele e espero que minhas costas se acostumem logo com o peso. E espero que a próxima geração de laptops homologados pela empresa seja de ultrabooks...
Apesar do Linux hoje ser o "mainstream" dos Unixes¹, eu gosto muito do Solaris e da sua elegância em resolver algumas coisas. Existe o sistema de arquivo deles, o ZFS - Zeta File System, mas também tem o zoneadm, para criação rápida e fácil de máquinas virtuais.
A maior vantagem é a facilidade mesmo de replicar uma nova máquina dentro do sistema. Invariavelmente preciso fazer testes, e essa possibilidade me permite ter uma máquina guest solaris dentro do próprio solaris em apenas alguns minutos.
É preciso criar o diretório, ou zonas como é chamado pelo Solaris, onde os sistemas hospedados ficarão. Eu sigo uma receita de bolo da Oracle/Sun e sempre utilizo o diretório "/zones", mas é preciso verificar a possibilidade de espaço antes.
A permissão é sempre 700 para evitar que outros usuários do sistema host possam ver os arquivos dos sistemas guests.
Na criação do sistema, é preciso definir seu caminho, IP e qual interface física conectada. Eu tentei utilizar a loopback, mas verifiquei que só funciona mesmo com a interface de rede.
Esse são os passos de exemplo pra criação da máquina virtual "fake-solaris":
[root@solaris ~]# mkdir /zones
# chmod 700 /zones
# zonecfg -z fake-solaris
fake-solaris: No such zone configured
Use 'create' to begin configuring a new zone.
zonecfg:fake-solaris> create
zonecfg:fake-solaris> set zonepath=/zones
zonecfg:fake-solaris> set autoboot=true
zonecfg:fake-solaris> add net
zonecfg:fake-solaris:net> set address=192.168.0.1
zonecfg:fake-solaris:net> set physical=lo0
zonecfg:fake-solaris:net> end
zonecfg:fake-solaris> verify
zonecfg:fake-solaris> commit
zonecfg:fake-solaris> exit
Em seguida é preciso usar o zoneadm para máquina virtual recém-criada para instalar o sistema operacional.
[root@solaris ~]# zoneadm -z fake-solaris install
Preparing to install zone .
Creating list of files to copy from the global zone.
Copying files to the zone.
Tanto a instalação quanto a remoção do sistema podem ser conseguidos facilmente com o zoneadm.
[root@solaris ~]# zoneadm -z fake-solaris uninstall
Are you sure you want to uninstall zone fake-solaris (y/[n])? y
Utilizando o comando "zoneadm list" é possível verificar as máquinas virtuais instaladas e seus estados correntes.
[root@solaris ~]# zoneadm list -cv
ID NAME STATUS PATH BRAND IP
0 global running / native shared
- fake-solaris incomplete /zones native shared
A máquina se encontra como "incompleta" pois falta fazer sua instalação. Seguida da instalação, é preciso fazer o "boot" da nova máquina, do contrário a mesma ficará no estado de "instalada" mas não no de "rodando", que é o estado da máquina virtual totalmente em funcionamento.
[root@solaris ~]# zoneadm -z fake-solaris install
Preparing to install zone .
Creating list of files to copy from the global zone.
Copying files to the zone.
Initializing zone product registry.
Determining zone package initialization order.
Preparing to initialize packages on the zone.
Initialized packages on zone.
Zone is initialized.
Installation of these packages generated errors:
Installation of packages was skipped.
Installation of these packages generated warnings:
The file contains a log of the zone installation.
[root@solaris ~]# zoneadm list -cv
ID NAME STATUS PATH BRAND IP
0 global running / native shared
- fake-solaris installed /zones native shared
You have new mail in /var/mail//root
[root@solaris ~]# zoneadm -z fake-solaris boot
[root@solaris ~]# zoneadm list -cv
ID NAME STATUS PATH BRAND IP
0 global running / native shared
1 fake-solaris running /zones native shared
É preciso então conectar na máquina como se fosse via console. Para isso existe o comando "zlogin". O parâmetro "-C" é para justamente definir a conexão como se fosse via console (ILOM/ALOM) e eu utilizo o "-e" para definir "#" para sair da sessão, do contrário o padrão fica como "~", o que em geral mata minha sessão ssh.
A definição de saída é para definir a tecla de "escape", que deve ser usada junto com ".". A sequência de saída do "zlogin" fica como "#." então.
O que se segue no restante das telas é o mesmo que uma instalação normal de solaris. O único ponto é que o nome da máquina virtual (zona) não precisa ser o mesmo hostname da máquina.
[root@solaris ~]# zlogin -C -e '#' fake-solaris
[Connected to zone 'fake-solaris' console]
Select a Language
0. English
1. es
2. fr
Please make a choice (0 - 2), or press h or ? for help: 0
Select a Locale
0. English (C - 7-bit ASCII)
1. Canada (English) (UTF-8)
2. Canada-English (ISO8859-1)
3. U.S.A. (en_US.ISO8859-1)
4. U.S.A. (en_US.ISO8859-15)
5. Go Back to Previous Screen
Please make a choice (0 - 5), or press h or ? for help: 3
What type of terminal are you using?
1) ANSI Standard CRT
2) DEC VT52
3) DEC VT100
4) Heathkit 19
5) Lear Siegler ADM31
6) PC Console
7) Sun Command Tool
8) Sun Workstation
9) Televideo 910
10) Televideo 925
11) Wyse Model 50
12) X Terminal Emulator (xterms)
13) CDE Terminal Emulator (dtterm)
14) Other
Type the number of your choice and press Return: 1
Creating new rsa public/private host key pair
Creating new dsa public/private host key pair
Configuring network interface addresses:.
─ Host Name ────────────────────────────────────────────────────────────────────
Enter the host name which identifies this system on the network. The name
must be unique within your domain; creating a duplicate host name will cause
problems on the network after you install Solaris.
A host name must have at least one character; it can contain letters,
digits, and minus signs (-).
Host name fake-solaris
────────────────────────────────────────────────────────────────────────────────
Esc-2_Continue Esc-6_Help
─ Confirm Information ──────────────────────────────────────────────────────────
> Confirm the following information. If it is correct, press F2;
to change any information, press F4.
Host name: fake-solaris
────────────────────────────────────────────────────────────────────────────────
Esc-2_Continue Esc-4_Change Esc-6_Help
─ Time Zone ────────────────────────────────────────────────────────────────────
On this screen you must specify your default time zone. You can specify a
time zone in three ways: select one of the continents or oceans from the
list, select other - offset from GMT, or other - specify time zone file.
> To make a selection, use the arrow keys to highlight the option and
press Return to mark it [X].
Continents and Oceans
──────────────────────────────────
- [ ] Africa
│ [X] Americas
│ [ ] Antarctica
│ [ ] Arctic Ocean
│ [ ] Asia
│ [ ] Atlantic Ocean
│ [ ] Australia
│ [ ] Europe
v [ ] Indian Ocean
────────────────────────────────────────────────────────────────────────────────
Esc-2_Continue Esc-6_Help
─ Country or Region ────────────────────────────────────────────────────────────
> To make a selection, use the arrow keys to highlight the option and
press Return to mark it [X].
Countries and Regions
─────────────────────────────────
- [ ] United States
│ [ ] Anguilla
│ [ ] Antigua & Barbuda
│ [ ] Argentina
│ [ ] Aruba
│ [ ] Bahamas
│ [ ] Barbados
│ [ ] Belize
│ [ ] Bolivia
│ [ ] Bonaire Sint Eustatius & Saba
│ [X] Brazil
│ [ ] Canada
v [ ] Cayman Islands
────────────────────────────────────────────────────────────────────────────────
Esc-2_Continue Esc-6_Help
─ Time Zone ────────────────────────────────────────────────────────────────────
> To make a selection, use the arrow keys to highlight the option and
press Return to mark it [X].
Time zones
──────────────────────────────────────────────────────
- [ ] Atlantic islands
│ [ ] Amapa, E Para
│ [ ] NE Brazil (MA, PI, CE, RN, PB)
│ [ ] Pernambuco
│ [ ] Tocantins
│ [ ] Alagoas, Sergipe
│ [ ] Bahia
│ [X] S & SE Brazil (GO, DF, MG, ES, RJ, SP, PR, SC, RS)
│ [ ] Mato Grosso do Sul
│ [ ] Mato Grosso
│ [ ] W Para
│ [ ] Rondonia
v [ ] Roraima
────────────────────────────────────────────────────────────────────────────────
Esc-2_Continue Esc-6_Help
─ Confirm Information ──────────────────────────────────────────────────────────
> Confirm the following information. If it is correct, press F2;
to change any information, press F4.
Time zone: S & SE Brazil (GO, DF, MG, ES, RJ, SP, P>
(Brazil/East)
────────────────────────────────────────────────────────────────────────────────
Esc-2_Continue Esc-4_Change Esc-6_Help
─ Root Password ────────────────────────────────────────────────────────────────
Please enter the root password for this system.
The root password may contain alphanumeric and special characters. For
security, the password will not be displayed on the screen as you type it.
> If you do not want a root password, leave both entries blank.
Root password: ******
Root password: ******
────────────────────────────────────────────────────────────────────────────────
Esc-2_Continue Esc-6_Help
rebooting system due to change(s) in /etc/default/init
[NOTICE: Zone rebooting]
SunOS Release 5.10 Version Generic_147441-09 64-bit
Copyright (c) 1983, 2011, Oracle and/or its affiliates. All rights reserved.
Hostname: fake-solaris
[root@solaris ~]# zlogin -C -e '#' fake-solaris
[Connected to zone 'fake-solaris' console]
Eu sempre sigo o site da Oracle para referência na criação e gerenciamento de máquinas virtuais:
[1] Linux não é derivado do Unix, como o FreeBSD. Ele é um projeto que se baseia no Minix.
Esse ano consegui me organizar e participar de um FLISOL, festival latino-americano de instalação de software livre. Não só participar: participar mesmo, inclusive da organização. Fiquei responsável pelo "installfest", para instalação de qualquer sistema livre.
Enquanto muitos associam "software livre" com Linux, eu fui além e preparei instalações para a família BSD: NetBSD, OpenBSD e FreeBSD. Eu poderia ter incluído o OpenSolaris, mas achei que já seria muito preciosismo de minha parte.
Eu baixei as seguintes imagens de sistemas, para instalar via boot remoto ou algum outro método:
No total foram 35 GB de imagens, incluindo AMD64 e i386, para atender máquinas com 32 bits ou 64 bits. E mesmo uma imagem para tentar instalar em MACs, caso alguém pedisse.
O saldo foi que somente um laptop apareceu para ser "atualizado" de um Ubuntu 8.04 ou algo assim. Após vários problemas, o sistema foi para 10.04 e... morreu. O laptop começou a apresentar problemas de leitura e escrita (o motivo de estar dando problemas no upgrade). E só. Nada mais para instalar.
Mesmo assim foi um evento agradável onde foi possível rever vários amigos e conhecer pessoalmente mais outros tantos. Como sempre, valeu a pena participar.
Essa são as fotos que fiz durante o evento.
UPDATED: 2021-12-23 atualizado pra export em javascript do próprio Flickr ao invés de flash.
Se um dia disserem que é verdade, negarei com todas as forças. Vamos dizer que essa história é uma ficção e que esse tipo de coisa nunca acontece nos meios corporativos.
Então toda e qualquer referência por aqui é pura imaginação minha, certo?
Pois então. Sabem o que é virose? Não? Não minha opinião, é algo genial criado pelos médicos. Já explico: pra quem tem filho, é comum ir ao médico pra ver alguma febre repentina que surge no meio da noite. E, na falta de um diagnóstico, é comum ouvir o termo "ah, isso é algum virose". Em geral trata-se com algum anti-termal (paracetamol ou algo do gênero) pra controlar a febre, e só. Tem de se esperar passar.
Pois uma vez eu trabalhava com um sistema de stream de vídeo, e o vídeo, vez ou outra, mostrava umas áreas "quadriculadas" por alguma perda de pacotes da rede. A questão é que a topologia estava exatamente assim:
O servidor de stream estava conectado num roteador de core, que ligava via fibra ótica (10 Gbps) ao switch core, que ligava no DSLAM. O DSLAM dividia a saída em 2 VLANs: uma pra Internet em geral, e outra específica pra TV. Não existia nada mais ligado nessa rede.
E quando é época de inferno astral, realmente não se tem muito o que fazer. Pois bem no dia em que estávamos testando isso, surge uma "visita" inesperada do diretor da conta de vendas, querendo ver como andavam os testes. No exato momento em que ele adentra a porta do recinto, a TV (talvez já mancomunada com algum ente espiritual maligno, algo como o exu-tranca-sistemas) resolve expor os pequenos pontos quadriculados.
A meia hora seguinte foi de sabatina de perguntas sobre o motivo dos quadriculados. Resolveu-se que aquilo era inaceitável e que a topologia deveria ser revista. Toda ela.
Não houve solução senão ir conectando o setupbox (a caixinha que convertia o stream pra saída de vídeo da TV) nos nós da rede para tentar detectar qual elemento estava falhando. Primeiro retiramos a parte DSL (DSLAM e modem), ligando diretamente no switch core. O quadriculado continuava lá.
Movemos diretamente para o roteador de core, apenas trocando a porta de fibra ótica para ethernet. E o quadriculado continuava lá.
Então conectamos diretamente no servidor de stream, para assim já decretar sua morte e dizer que tínhamos encontrado a origem do problema. E o vídeo passou normalmente...
Esse é o exato momento em que todo mundo fica com aquela cara de poker face.
Então resolvemos reconectar ao roteador, pois esse deveria ser o causador do problema. Tudo conectado, fomos aos testes e... vídeo funcionando perfeitamente. Nenhum problema aparente.
Então conectamos novamente ao switch core para verificar se o problema poderia ser a porta de via fibra ótica e...
Voltamos ao DSLAM e...
Assumimos que aquilo era obra do demônio, o exu-tranca-sistemas mesmo, e seguimos a vida em frente, ou melhor, continuamos com os testes.
Ao final do dia, recebo uma ligação de um alto escalão querendo saber se o problema havia sido resolvido. Expliquei gentilmente que sim, e que todos os elementos de rede tinham sido revisados. Então recebi a pergunta fatídica: qual era a origem do problema?
Sem titubear, respondi:
- Virose de rede, mas já estamos administrando 10 pings de 4 em 4 horas, por 7 dias, para evitar inflamações nos links.
E tudo teria terminado aí, se não houvesse uma apresentação para altos executivos.
No dia da tal apresentação, apareceram os distintos senhores, todos devidamente engravatados. E começou-se a apresentação. Eu, por ser um cara muito técnico, apenas fiquei ao fundo da sala assistindo a apresentação, que era ministrada por alguém que eu nunca tinha visto na vida, e que estava também devidamente engravatado. E falava com bastante segurança sobre os testes realizados. E tudo corria bem e tranquilo, com exibição perfeita do vídeo, quando, ao final da apresentação, o engravatado soltou em alto e bom som:
- E durante os testes, nossos técnicos encontraram uma virose de rede. Mas eles trabalharam arduamente para elinimar esse vírus e agora garantem que os links não ficarão inflamados, não afetando a performance do vídeo.
Tive de sair da sala para não engasgar de tanto rir.
Desde o fim do ano passado, tenho percebido que o Estadão resolveu colocar um filtro de conteúdo em alguns de seus artigos na web.
Como o conteúdo pertence ao jornal, eles têm todo o direito de fazer esse tipo de abordagem. Mas o que eu acho chato é que eles publicam esses artigos no twitter, e depois enfiam na sua cara o bloqueio.
Enfiam? Será?
Se enfiam na cara, quer dizer que roda na minha máquina e não na deles, certo? Então eu posso dizer para meu navegador (no caso o Google Chrome) "não" ler esse bloqueio, não posso? Claro que sim!
Depois de uma procura no código da página, encontrei um javascript que chama uma função fadeOut() para criar esse efeito. Bastou então achar o arquivo javascript com tal função. Pra isso contei ajuda do browser por linha de comando Lynx e um pouco de shell script.
for link in $(lynx \
-source -dump \
"http://www.estadao.com.br/noticias/esportes,pistorius-rejeita-acusacao-de-assassinato-da-namorada,997339,0.htm" | \
grep js | \
sed "s/.*src=\"//" | \
grep estadao | \
sed "s/\".*//" | \
sed "s|^/|http://www.estadao.com.br/|" | \
grep -v img.estadao)
do
echo $link
lynx -dump -source "$link" | \
grep -i fadeout && \
echo "ACHEI: $link" && \
break
done
Então consegui achar que o vilão é o javascript de jquery:
http://www.estadao.com.br/estadao/novo/js/jquery-1.5.2.min.js
Bastou então usar o AdBlock Plus pra bloquear esse arquivo e tudo funcionou novamente.
Finalmente resolvi publicar alguma coisa no slideshare. Não que eu tenha tanta coisa assim pra compartilhar, mas estava ficando envergonhado de receber vários pedidos para "seguir" pessoas por lá, uma vez que nunca publiquei absolutamente nada.
Então fiz o upload de algumas apresentações antigas, realizadas entre 2002 e 2005 (acho), que fiz para eventos do Debian-SP, GTER (Grupo de Trabalhos de Engenharia de Redes, ligado ao Nic.BR) e Maratona HOWTO, esse último um evento de HOWTOS que foi ideaizado pela 4Linux, se não estou enganado.
São assunto variados, indo de roteamento avançado e controle de banda à PABX IP com Asterisk. Provavelmente devem estar obsoletos, uma vez que faz mais de 10 anos que foram escritos, mas... ao menos publiquei algo por lá ;-)
Leap of faith, ou salto de fé, é um passo no vazio que se dá durante a série de jogos "Assassins Creed". Basicamente significa "fechar os olhos e acreditar que vai dar certo". Durante o jogo, existem lugares já marcados para usar o "salto da fé", onde em geral existem pombas, mas na vida real, nem tanto.
Não que eu tenha tentado pular da varanda de casa, nem tentado assassinar ninguém. Nada disso. Mas esses dias eu fiz um "salto de fé" ao cancelar meu serviço de banda larga do Net Virtua e assinar o de fibra óptica da TIM. Como não existem muitas instalações e descrições, foi um passo seguido de fé, muita fé...
O acesso não é caro: paga-se por volta de R$ 60,00 por 35 Mbps de downstream e 20 Mbps de upstream. Por mais ou menos R$ 50,00, o Net Virtua me fornecia somente 1 Mbps. E esse não era o único problema com o Virtua: a latência de rede era o pior. Simplesmente estava impossível de fazer qualquer coisa com o link, pois tudo tinha uma latência absurda, fazendo vídeos do Youtube engasgarem mesmo com a menor qualidade, e tornando impossível jogar jonline, como com "call of duty", na PSN do Playstation. Não sei se é QoS mal feito do lado da Net, ou o que pode ser, mas com certeza não era o fato de ter somente 1 Mbps que fazia a diferença, pois tenho a mesma banda em outro lugar, também pelo Net Virtua, e não sofro desse problema.
Pela monitoração do link, dava pra ver que dificilmente essa banda era totalmente utilizada. Mesmo sem tráfego na rede, os tempos de respostas de ping alcançavam valores próximos de 800 ms, o que mudou para 10 ms em geral com o link da TIM.
helio@shibboleet:~$ ping -c 10 helio.loureiro.eng.br
PING helio.loureiro.eng.br (200.160.198.15) 56(84) bytes of data.
64 bytes from cp01-tvt-db.durand.com.br (200.160.198.15): icmp_req=1 ttl=50 time=10.6 ms
64 bytes from cp01-tvt-db.durand.com.br (200.160.198.15): icmp_req=2 ttl=50 time=10.1 ms
64 bytes from cp01-tvt-db.durand.com.br (200.160.198.15): icmp_req=3 ttl=50 time=10.1 ms
64 bytes from cp01-tvt-db.durand.com.br (200.160.198.15): icmp_req=4 ttl=50 time=10.7 ms
64 bytes from cp01-tvt-db.durand.com.br (200.160.198.15): icmp_req=5 ttl=50 time=10.2 ms
64 bytes from cp01-tvt-db.durand.com.br (200.160.198.15): icmp_req=6 ttl=50 time=11.3 ms
64 bytes from cp01-tvt-db.durand.com.br (200.160.198.15): icmp_req=7 ttl=50 time=10.0 ms
64 bytes from cp01-tvt-db.durand.com.br (200.160.198.15): icmp_req=8 ttl=50 time=10.1 ms
64 bytes from cp01-tvt-db.durand.com.br (200.160.198.15): icmp_req=9 ttl=50 time=10.0 ms
64 bytes from cp01-tvt-db.durand.com.br (200.160.198.15): icmp_req=10 ttl=50 time=11.2 ms
--- helio.loureiro.eng.br ping statistics ---
10 packets transmitted, 10 received, 0% packet loss, time 9013ms
rtt min/avg/max/mdev = 10.006/10.469/11.338/0.498 ms
E justamente pela falta de comentários sobre o Live TIM, fibra óptica, que resolvi escrever um pouco sobre o mesmo.
Primeiro que não é um serviço de fibra que chega em casa, o FTTH (Fiber To The Home). É mais um FTTB (Fiber To The Building), pois a fibra óptica chega até o DG (Distribuidor Geral) do prédio, que fica no térreo, e daí é convertido por um DSLAM em VDSL, que então sobe para residência pelo sistema de par trançado de cobre, usado pela telefonia. Na residência, ou melhor, no apartamento, é preciso um modem (CPE) de VDSL para converter esse sinal em rede ethernet.
Nesse ponto existe um lado que pode ser tanto ruim quanto bom: o CPE. É um modem da ZTE fornecido pela TIM que levanta uma sessão PPPoE com a rede, recebendo o IP válido, e faz NAT de saída. O serviço da TIM gentilmente fornece o login e senha de administração pra poder alterar os parâmetros (admin/admin), mas o CPE usa um firmware completamente limitado, que não permite mudar muita coisa. É possível configurar o wifi que vem embutido e o endereçamento interno, mas acaba por aí. Isso me levou a ter 2 nívels de NAT na minha rede interna: o já existente no roteador TP-Link TL-WR1043ND e que roda DD-WRT, e esse segundo NAT do CPE da ZTE. Com isso, não consigo mais acessar por ssh as máquinas internas da minha rede.
Como não consegui acessar a portas das máquinas internas, utilizando port fowarding, não sei dizer se está faltando configuração no CPE ou se a TIM bloqueia as portas. Isso no momento é chato, mas não é um problema que me faça voltar a usar o Net Virtua. E também não quero desligar meu roteador com DD-WRT, pois o mesmo me ajuda a monitorar a rede com SNMP, entre outras coisas. Eu testei a colocação de uma máquina logo atrás do CPE, com o roteamento de porta, e o mesmo não funcionou. Então estou acreditando que a TIM realmente BLOQUEIA as portas ou o tráfego entrante.
Tentei fazer a configuração do DD-WRT totalmente em bridge, mas não consegui até o momento. Então esse é um ponto negativo do Livre TIM: utilizar um PPPoE com NAT no modem sem possibilidade de mudar. Como o acesso fornecido não tem limitação de quantidade de dados, não entendi muito bem o motivo de usar o PPPoE - outro ponto que não vou classificar como negativo, mas diria que desnecessário. Outra coisa que fiquei decepcionado foi em relação ao tipo de IP recebido: somente IPv4. Eu já estava salivando de excitação esperando um IPv6 também. Mas como o CPE é novo, provavelmente deve suportar upgrade.
Dos pontos positivos, a banda, o custo e o fato de não ter nem custo de instalação, nem contrato de serviço, podendo ser interrompido a qualquer momento. Testei fazer download utilizando até 20 Mbps de downstream, com 10 de upstream liberado, e jogar ao mesmo tempo. O resultado foi fantástico: sem problemas, nem latências, nem travamentos. Ainda mandei um stream de vídeo no Youtube com mais um stream do NetFlix, ambos em HD, e... sem problema algum!
Foi um realmente um salto de fé no escuro, mas aparentemente o serviço IP da TIM é muito melhor que seu serviço de telefonia. Não estou arrependido, mas só vou poder dar uma opinião sobre a qualidade geral do serviço após 6 meses de uso, no mínimo.
Atualização: Fri Feb 15 13:45:53 BRST 2013
Justamente quando estava escrevendo sobre a banda larga da TIM, fiquei quase 24 horas sem Internet.
Em termos de acesso à rede, isso é quase uma eternidade, o que desencadeou minha síndrome de abstinência internética. Durante esse período, consegui acessar uma rede Wi-Fi de algum vizinho, que estava generosamente aberta sem senha alguma. Nisso fui informado pelos amigo que o problema era um rompimento de fibra óptica, justamente na minha região.
Realmente foi muito azar ou acaso. Acabei indo viajar até o carnaval, o motivo pelo qual não terminei de escrever e publicar esse post e só voltar a ele agora.
Mas após esse incidente, o link voltou e está funcionando sem problemas.
Page 18 of 33