Shared posts

19 Aug 19:22

Como o Docker pode resolver problemas do mundo real para desenvolvedores web

by Thomas Peham

Trabalhando com desenvolvimento web? Bem, então você provavelmente já ouviu falar sobre Docker e seus desdobramentos recentes. Recipientes Docker podem ser um verdadeiro reforço de produtividade para as suas próximas aplicações web. Para um desenvolvedor web, não é tão fácil de entender a essência do Docker.

É por isso que eu gostaria de dar uma olhada nos recipientes Docker e mostrar alguns problemas do mundo real que o Docker está resolvendo para desenvolvedores web.

docker-1

O que é o Docker?

Docker é basicamente uma ferramenta de código aberto para a execução de containers isolados no Linux fazendo o deploy de aplicativos dentro de containers isolados mais rapidamente. O Docker cria recipientes autossuficientes e portáteis a partir de qualquer aplicativo.

O mesmo recipiente que o desenvolvedor cria e testa em seu PC pode ser executado em produção, através de máquinas virtuais, na nuvem ou quaisquer outros lugares.

docker-2

Você pode executar um único serviço por container, por exemplo, um recipiente para seu MySQL, um recipiente para o Apache e um recipiente para a sua instalação do WordPress.

Caso contrário, você pode colocar uma pilha de todo o aplicativo em um recipiente conjugado. Não há certo ou errado sobre isso.

Recipientes Docker vs. máquinas virtuais

A capacidade de separar um aplicativo do sistema operacional subjacente Linux é muito atraente. Comparar recipientes Docker com máquinas virtuais é uma coisa válida, embora recipientes Docker não substituam máquinas virtuais. As máquinas virtuais têm basicamente um sistema operacional completo com o seu próprio gerenciamento de memória, drivers de dispositivo etc. Em contraste, os recipientes Docker compartilham o sistema operacional do anfitrião e são, portanto, muito mais fáceis de gerenciar.

docker-3

Container e Container-as-a-Service

Os containeres estão no mercado por um bom tempo. E embora nunca realmente tenham se tornado um “padrão da indústria”, o Docker tornou tudo isso possível. Com uma ampla gama de suporte e fácil de aprender, o Docker está aqui para ficar.

O Docker é basicamente construído em cima de LXC (Linux Containers), mas definitivamente não é um substituto para o LXC, uma vez que o Docker oferece alguns recursos de alto nível no topo do LXC, tais como controle de versões e implantação portátil através de máquinas. Eu gostaria de recomendar este artigo do site StackOverflow como referência.

O crescimento do negócio de Container-as-a-Service é imenso. No início de 2015, o Docker publicou um infográfico mostrando o crescimento dos downloads de containers e o número de aplicações sendo utilizadas em recipientes Docker, além de algumas outras métricas.

(Todo o infográfico pode ser encontrado neste link para consulta.

Casos de uso do mundo real para desenvolvedores web

O Docker foi basicamente concebido de forma que possa ser usado em muitos casos de uso diferentes. Além dos casos de uso mencionados no site docker.com, eu gostaria de dar uma olhada nos casos de uso seguintes, nos quais a tecnologia do Docker fornece um ótimo e consistente ambiente.

Grande comunidade em torno do Docker

A melhor coisa sobre o Docker é que ele está pronto para usar. Com a sua crescente comunidade de desenvolvedores, existem milhares de containeres prontos para executar aplicativos populares, como MySQL ou WordPress.

Se você deseja executar o WordPress, por exemplo, pode baixá-lo a partir do Docker Hub e executá-lo com esta única linha de código:

docker run –name some-wordpress –link some-mysql:mysql -d wordpress

Uma grande vitória para o desenvolvimento local

Como um desenvolvedor web, você pode se desenvolver em seu ambiente local. Minimizar as diferenças entre seu ambiente local e produção nos ajuda a evitar mudanças de última hora em caso de diferenças na configuração.

Trabalhar com containers Docker no ambiente local é um verdadeiro reforço na produtividade e definitivamente poupa algum aborrecimento de último minuto.

Implementação rápida

Nós vimos algumas aplicações fantásticas nas últimas décadas, criadas a partir de hardware real e de servidores virtuais para o Docker. A criação de novos recursos de hardware provavelmente levaria vários dias. Com a virtualização, ela passou para apenas alguns minutos.

Com o Docker, você pode ter tudo instalado e funcionando dentro de alguns segundos. Simplesmente criando um container e não inicializando todo um sistema operacional, nós definitivamente vamos economizar algum tempo.

docker-4

Isolamento do aplicativo para um sandbox seguro

Com o Docker, você basicamente executa um aplicativo ou processo por container. Containers tiram vantagem da capacidade de criar ambientes isolados. Cada recipiente é atribuído ao seu próprio ambiente em tempo de execução, e cada container único recebe sua própria pilha e o processo único no espaço da rede.

Se você deseja instalar diferentes versões do Python ou qualquer outra biblioteca, linguagem ou programa, os containers Docker são a sua solução. Você pode simplesmente instalar uma biblioteca em um container, compará-la com uma versão diferente localizada em outro container, brincar com ela e jogá-la fora depois sem qualquer risco.

Benefícios de segurança dos containers

Executar vários containers pode fornecer alguns benefícios de segurança. Ao executar aplicativos em vários containers, cada um deles só tem acesso às portas e arquivos explicitamente expostos pelo outro container.

Mais adiante, containers devem oferecer um maior nível de controle sobre os dados e software que são instalados. A vantagem é que executar o software em um container não afetará qualquer outro recurso em uma máquina.

As atualizações são um importante problema de segurança. A execução de aplicativos em um ambiente Docker faz com que o processo de atualização seja menos doloroso.

Teste simplificado

Configurar ambientes de teste com containers Docker é super fácil. Pensando em todas esses frameworks diferentes e bancos de dados, bem como em diferentes versões do Python, por exemplo, os testes em um ambiente virtualizado tornaram-se um verdadeiro desafio.

Através da criação de diferentes recipientes Docker para testes, você pode acelerar drasticamente sua suíte de testes, separando versões diferentes em diferentes containers.

docker-5

Fácil configuração

Uma das muitas razões para o uso cada vez mais crescente dos containers Docker é definitivamente a configuração simples e fácil de gerenciar. Com máquinas virtuais, é possível executar qualquer aplicação com sua própria configuração em cima de sua infraestrutura já existente. O Docker basicamente fornece a mesma capacidade de processamento, mas sem a sobrecarga de uma máquina virtual. No entanto, os recipientes Docker não podem substituir máquinas virtuais. Isso permite que você dissocie os requisitos de infraestrutura do ambiente de aplicação.

Dockerize seu desenvolvimento web?

“Containerizar” suas aplicações não só irá tornar a sua implementação mais rápida, mas também muito mais fácil. A portabilidade e a flexibilidade adquiridas com containers Docker são imensas. Desenvolvedores web podem evitar a sobrecarga de seu ambiente de desenvolvimento usando Docker.

***

Thomas Peham faz parte do time de colunistas internacionais do iMasters. A tradução do artigo é feita pela redação iMasters, com autorização do autor, e você pode acompanhar o artigo em inglês no link: http://usersnap.com/blog/docker-for-web-developers/

 

Mensagem do anunciante:

Acesse e conheça as oportunidades para empresas de software. Torne-se Parceiro de Software Intel®

18 Aug 21:16

Gotas de orvalho (9)

by Francisco Nunes
O sustento ao nascer do dia

A Bíblia ensina uma revelação dupla e consistente. Assim como os leitores corretamente esperarm que a válida interpretação de Isaías seja consistente com a de Marcos, do mesmo modo eles podem esperar que a acurada interpretação dos fatos da natureza seja consistente com a mensagem de Gênesis e do restante da Escritura.

(Hugh Ross)

O Senhor, Deus onipotente, reina. Seu governo é exercido sobre a matéria inanimada, sobre os animais ferozes, sobre os filhos dos homens, sobre anjos bons e maus e sobre o próprio Satanás. Nenhuma rotação de um planeta, nenhum brilhar de uma estrela, nenhuma tempestade, nenhum movimento de qualquer criatura, nenhuma ação dos homens, nenhuma mensagem dos anjos, nenhum ato do Maligno — nada em todo o vasto universo pode vir a acontecer sem que Deus tenha eternamente estabelecido. Esse é um fundamento para a fé. Esse é um lugar de repouso para o intelecto. Essa é uma âncora para a alma, tanto firme quanto segura. Não é um destino cego, um mal desenfreado, o homem ou o Diabo, mas o Senhor Todo-poderoso que está governando o mundo, governando de acordo com Seu bom prazer e com Sua eterna glória.

(A. W. Pink)

As coisas comuns deste mundo não são meros artefatos da cultura, ferramentas da esfera natural, mas, em vez disso, preciosos dons de nosso Pai.

(R. C. Sproul Jr.)

Prefiro estar no coração da África dentro da vontade de Deus do que estar no trono da Inglaterra fora de Sua vontade.

(David Livingstone)

Nosso Pai celestial nunca toma nada terreno de Seus filhos, a menos que tenha planos de lhes dar, em troca, algo melhor.

(George Müller)

Send to Kindle

O post Gotas de orvalho (9) apareceu primeiro em Campos de Boaz.

18 Aug 21:07

Verdadeira ou falsa? (Don Fortner)

by Francisco Nunes
Mesmo parecendo ser verdadeira, é falsa
  1. A fé falsa pode ser muito iluminada e grande conhecedora da verdade do evangelho. Judas era. A verdadeira fé recebe o amor da verdade (2Ts 2.10).
  2. A fé falsa excita os afetos, como os ouvintes do solo pedregoso da parábola (Mt 13), e leva as pessoas a surgir como estrelas cadentes, apenas para desaparecerem rapidamente. A verdadeira fé é o dom permanente e crescente de Deus.
  3. A fé falsa reforma a vida exterior e faz as pessoas viverem melhor diante dos homens. A verdadeira fé nasce de um coração regenerado e leva as pessoas a procurarem a vontade e a glória de Deus.
  4. A fé falsa pode falar bem de Cristo, como os judeus fizeram. A verdadeira fé ama Cristo (1Pe 1.8).
  5. A fé falsa confessa pecados como o rei Saul (1Sm 24.16-22). A verdadeira fé confessa o pecado como Davi (Sl 51).
  6. A fé falsa pode humilhar-se em pano de saco e cinza, como Acabe (1Rs 21.27-29). A verdadeira fé se humilha diante de Deus.
  7. A fé falsa pode arrepender-se em terror, como Esaú e Judas. A verdadeira fé se arrepende em contrição, sendo convencida do caminho da salvação de Deus em Cristo.
  8. A fé falsa muitas vezes realiza obras religiosas com muito afinco. Saulo de Tarso o fez. A verdadeira fé é uma fé que “opera por amor”.
  9. A fé falsa é, por vezes, muito generosa e caridosa (Ananias e Safira; At 5). A verdadeira fé faz com que pecadores resgatados sejam generosos, de bom grado, constrangidos apenas por amor e gratidão.
  10. A fé falsa pode tremer da Palavra de Deus, como Félix (At 24.25). A fé verdadeira treme e se curva.
  11. A fé falsa freqüentemente experimenta muito na religião. A fé verdadeira não confia em nenhuma experiência, não importa quão grande seja, e olha somente para Cristo.
  12. A fé falsa freqüentemente goza de grandes privilégios religiosos, como a mulher de Ló (Gn 19.1-26). A verdadeira fé coloca não nenhuma confiança na carne.
  13. A fé falsa pode pregar, fazer milagres e expulsar demônios, como Judas. A fé verdadeira se alegra em ter o nome escrito no céu.
  14. A fé falsa muitas vezes alcança um alto cargo na igreja, como Diótrefes (3Jo), e caminha com grandes pregadores, como Demas andou com Paulo (Cl 4.14; Fm 24; 2Tm 4.10). A fé verdadeira se sente honrada por cuidar das portas da casa de Deus e caminhar com Cristo.
  15. A fé falsa pode ser pacífica e carnalmente confiante, como as cinco virgens loucas (Mt 25.1-13). A fé verdadeira nada pressupõe, mas olha constantemente para Cristo (Hb 12.2).

 

(Traduzido por Francisco Nunes. Este artigo pode ser distribuído e usado livremente, desde que não haja alteração no texto, sejam mantidas as informações de autoria e de tradução e seja exclusivamente para uso gratuito. Preferencialmente, não o copie em seu sítio ou blog, mas coloque lá um link que aponte para o artigo.)

Send to Kindle

O post Verdadeira ou falsa? (Don Fortner) apareceu primeiro em Campos de Boaz.

22 Jul 23:14

BGP and the System of Trust that Runs the Internet, Pt. 2

by Owen Lystrup

Editor’s note: This post is the second in a two-part series on BGP. Read part one here.

The last half-decade has witnessed a number of events that perfectly exemplify what happens when BGP goes wrong. Whether caused purposely by malicious attackers or by accident from routing leaks, the effect is essentially the same: everyone has a bad time. In these cases, many companies and content providers end up becoming collateral damage even if they aren’t directly involved. BGP includes a concerning element in its ability to affect nearly every major Internet service within a short time frame. But what’s most surprising about the protocol, which is in charge of routing nearly all the Internet’s traffic, is that it runs on a system of trust between providers.

The Internet’s Telephone Game
BGP can get complicated, being at the core of what can go wrong with Internet routing. It starts with what are known as Autonomous systems (AS).

An autonomous system is a collection of IP networks managed autonomously–hence the name–under one routing policy.

AS Route

Image from Shutterstock

Each AS gets a unique number (ASN) to identify itself from the regional Internet registry. Each AS is connected to at least one other AS, which will connect it to the rest of the Internet.

A single AS can be connected to dozens or even hundreds of other ASNs, through what is called peering (see part one). It’s easy to picture the entire Internet as a graph, with each node on the graph representing an AS.

Each AS in the graph tells the rest of the Internet via its neighbors for which IP networks (often called prefixes) it is willing to receive traffic. This process is often referred to as “announcing.”

Andree Toonk, founder of BGPmon and manager of network engineering at OpenDNS, says that announcing is the way for a company to establish which prefixes it would like the world to know. Essentially it’s a way of posting a billboard on the Internet superhighway to say, “Hey, I’m GoodShoes, Inc.! And I’m over here!” Routers then use that information to find the best route to that company.

This process is important because there are announcements that are only supposed to stay between two ASNs, not intended for further external use. When one of those ASNs propagates the announcement for the prefixes to the world incorrectly, it is called a “leak.” Leaks happen fairly regularly, and are typically due to configuration a mistake. As a result, traffic is redirected through a different network, which can cause issues like performance problems and security related concerns.

BGP hijacks are a similar problem. With a BGP leak, an AS inserts itself in the middle of a path, but in a hijack an AS simply claims it owns the prefixes and should receive all traffic for it.

BGP Leaks: Simple, Yet Costly
Tier 1 provider Level3 recently became an unfortunate case study on the drastic effects of a mistaken BGP leak.

It started when a Malaysian ISP incorrectly announced a large amount of routes–BGPmon estimates about 179,000 of them.

Malaysia Telekom Routes

Image: BGPMon.net

Level3 then incorrectly accepted those routes as good, and re-routed  a massive flood of traffic to the ISP in Malaysia, by propagating the new routes to all its customers. It was a flood Telekom Malaysia did not intend, and was not equipped to handle, which then began dropping packets on a large scale. This event is essentially a mistaken “man-in-the-middle.” As a result, a number of major Internet services like Snapchat, Skype, and Google ended up having services degraded for about three hours.

Three hours might not seem like much time, but in Internet time where millions of transactions take place every second, it can be extremely costly. And, according to Toonk, there’s a number of different ways these can occur and aside from some basic filtering, there’s not much to prevent them from happening.

“There’s a whole philosophical debate as to who owns more responsibility in incidents like these,” he said. “Given how large Level3 is, and its pivotal role on the Internet, it has the greater responsibility in fixing issues like this because it’s what the company does. But obviously if the Malaysian telecom [company] had not made the error in the first place, it never would have happened.”

BGP Hijacks: Simple, Yet Profitable
One famous example of an entity conducting a BGP hijack on purpose was the Turkish hijack of Google DNS, OpenDNS, and Spray painted DNSLevel3 in the spring of 2014. At the time, a corruption scandal was brewing, and to circumvent blocks placed on Twitter and YouTube by large ISPs in Turkey, civilians began using free DNS services. In a ploy to stop the dissenters from spreading their message, Turk Telekom began hijacking DNS traffic using BGP announcements.

Malicious hijacking can cause some damaging results. Toonk commented that if a hijack is successful, “the rate of impact can be severe.”

But not all are politically motivated. Some are monetarily motivated, like the case of a large-scale hijack affecting at least 19 ISPs conducted by an attacker looking to steal Bitcoins. Going back to the concept of time during these sorts of attacks–or even in mistaken leaks like the one involving Malaysia Telekom–every second is damaging. The hacker who perpetrated the Bitcoin theft averaged around 30 seconds during each traffic hijack. Even so, after at least 22 attacks, it was enough time for him to steal around $9,000 a day, and an estimated $83,000 total.

Routing Better: Time for a BGP Change
Hijacks and leaks occur because the BGP framework–the system that runs the entire Internet–currently operates on a system of trust, and wasn’t designed with security built into it. There is currently no easy way to verify information from a provider.

“In BGP I just have to trust whatever other providers are telling me, is true,” Toonk said. “But there’s no way to verify for sure. On the web, for instance, we have HTTPs. With a certain degree of trust, you can tell if the site you’re on is legitimate. With BGP, if you say you can reach Google, I just have to trust that is true.”

And currently, Toonk said, there’s no easy way for the owner of an IP network to even prevent leaks and hijacks from occurring. ISPs and users of BGP can only monitor for incorrect routing events. This reality was confirmed by Job Snijders, an IP developer for NTT America, a major Tier 1  ISP.

According to Snijders, there were a number of measures Level3 could have taken before and following the major route leak on June 12. He referenced an open letter to Level3 that suggested a number of measures the provider could have taken to prevent the leak from happening in the first place. One was maximum prefix limits–a way of setting a maximum number of new prefixes a peer can announce. Snijders said it’s up to providers and routers to change their behavior to prevent new announcements and routing changes from being accepted in bulk automatically.

Some of the responsibility to prevent leaks also falls on manufacturers. Routers are by default often set to advertise every route they can possibly reach. “It would be a great win if manufacturers would provide network operators with a configuration knob that changes this default behavior ,” he said. “Leaks occur when filters don’t properly prevent this from happening.”

A public key infrastructure called RPKI (resource public key infrastructure) could also help validate ASNs and IPs, but similar to DNSSEC, it’s running into difficulties with adoption, as not everyone in the industry is convinced it is the best fix.

However, not all preventative measures need to be highly technical. Toonk says monitoring like the type that BGPMon provides can be a huge help in limiting attack or leak time and troubleshooting efforts. Proper filtering on the ISP side can also prevent a lot of issues.

Or, as Snijders added, sometimes it might be as simple as picking up the phone. “When you see a route leak incident happen, get on the phone,” he said. “It doesn’t matter whether you are a customer, supplier, or just a bystander. Literally keep calling until you get through to someone who can fix the issue.”

In the end, the system of trust that is holding up the Internet can also be used for good. “Perseverance always wins,” Snijders said. “We’re in this together. We need to help each other.”

 

The post BGP and the System of Trust that Runs the Internet, Pt. 2 appeared first on OpenDNS Blog.

19 Jul 07:43

Gmail enfim ganha recurso de “desenviar” e-mails do Labs e Inbox

by Ronaldo Gogoni

gmail

Todo mundo já passou por isso: você escreve um e-mail, seleciona os contatos e envia, apenas para descobrir aterrorizado que incluiu uma pessoa na lista que não poderia, em hipótese alguma receber aquela mensagem. Isso quando não esquecemos de dizer alguma coisa ou deixamos alguém de fora. Aí você era obrigado a correr atrás e escrever uma mensagem de correção, um pedido de desculpas, mas na maioria das vezes só nos restava aguardar o Mjolnir descer com força nas ideias.

Usuários do Gmail Labs não passam por esse problema, pois desde 2009 estes contam com um recurso muito útil chamado “Desfazer Enviar”. Ele foi adicionado ao Inbox no ano passado, mas o Gmail mesmo não tinha acesso a ele. Até agora.

Foram precisos seis anos, mas o cliente para web finalmente conta com a função de cancelar o envio de e-mails. Agora, quando você dispara uma mensagem há um delay pré-determinado, dando ao usuário a chance de cancelar o envio se perceber que fez alguma besteira. O tempo de atraso pode ser configurado entre 5 e 30 segundos.

Se você é usuário do Inbox ou do Gmail Labs muito provavelmente já utiliza o Desfazer Enviar, mas o recurso introduzido agora no cliente normal não está ativado por padrão. É preciso entrar em Configurações e na aba Geral, marcar a caixa “Ativar o cancelamento de envio”. Ali também é possível determinar de quantos segundos será o delay.

gmail-config

Assim, quando você enviar um e-mail a opção “Desfazer” aparecerá ao lado da notificação de envio, e basta clicar nela para evitar um sem número de dores de cabeça.

Fonte: Google.

The post Gmail enfim ganha recurso de “desenviar” e-mails do Labs e Inbox appeared first on Meio Bit.








17 Jul 19:47

Introducing the Fan – simpler container networking

by Mark Shuttleworth

Canonical just announced a new, free, and very cool way to provide thousands of IP addresses to each of your VMs on AWS. Check out the fan networking on Ubuntu wiki page to get started, or read Dustin’s excellent fan walkthrough. Carry on here for a simple description of this happy little dose of awesome.

Containers are transforming the way people think about virtual machines (LXD) and apps (Docker). They give us much better performance and much better density for virtualisation in LXD, and with Docker, they enable new ways to move applications between dev, test and production. These two aspects of containers – the whole machine container and the process container, are perfectly complementary. You can launch Docker process containers inside LXD machine containers very easily. LXD feels like KVM only faster, Docker feels like the core unit of a PAAS.

The density numbers are pretty staggering. It’s *normal* to run hundreds of containers on a laptop.

And that is what creates one of the real frustrations of the container generation, which is a shortage of easily accessible IP addresses.

It seems weird that in this era of virtual everything that a number is hard to come by. The restrictions are real, however, because AWS restricts artificially the number of IP addresses you can bind to an interface on your VM. You have to buy a bigger VM to get more IP addresses, even if you don’t need extra compute. Also, IPv6 is nowehre to be seen on the clouds, so addresses are more scarce than they need to be in the first place.

So the key problem is that you want to find a way to get tens or hundreds of IP addresses allocated to each VM.

Most workarounds to date have involved “overlay networking”. You make a database in the cloud to track which IP address is attached to which container on each host VM. You then create tunnels between all the hosts so that everything can talk to everything. This works, kinda. It results in a mess of tunnels and much more complex routing than you would otherwise need. It also ruins performance for things like multicast and broadcast, because those are now exploding off through a myriad twisty tunnels, all looking the same.

The Fan is Canonical’s answer to the container networking challenge.

We recognised that container networking is unusual, and quite unlike true software-defined networking, in that the number of containers you want on each host is probably roughly the same. You want to run a couple hundred containers on each VM. You also don’t (in the docker case) want to live migrate them around, you just kill them and start them again elsewhere. Essentially, what you need is an address multiplier – anywhere you have one interface, it would be handy to have 250 of them instead.

So we came up with the “fan”. It’s called that because you can picture it as a fan behind each of your existing IP addresses, with another 250 IP addresses available. Anywhere you have an IP you can make a fan, and every fan gives you 250x the IP addresses. More than that, you can run multiple fans, so each IP address could stand in front of thousands of container IP addresses.

We use standard IPv4 addresses, just like overlays. What we do that’s new is allocate those addresses mathematically, with an algorithmic projection from your existing subnet / network range to the expanded range. That results in a very flat address structure – you get exactly the same number of overlay addresses for each IP address on your network, perfect for a dense container setup.

Because we’re mapping addresses algorithmically, we avoid any need for a database of overlay addresses per host. We can calculate instantly, with no database lookup, the host address for any given container address.

More importantly, we can route to these addresses much more simply, with a single route to the “fan” network on each host, instead of the maze of twisty network tunnels you might have seen with other overlays.

You can expand any network range with any other network range. The main idea, though, is that people will expand a class B range in their VPC with a class A range. Who has a class A range lying about? You do! It turns out that there are a couple of class A networks that are allocated and which publish no routes on the Internet.

We also plan to submit an IETF RFC for the fan, for address expansion. It turns out that “Class E” networking was reserved but never defined, and we’d like to think of that as a new “Expansion” class. There are several class A network addresses reserved for Class E, which won’t work on the Internet itself. While you can use the fan with unused class A addresses (and there are several good candidates for use!) it would be much nicer to do this as part of a standard.

The fan is available on Ubuntu on AWS and soon on other clouds, for your testing and container experiments! Feedback is most welcome while we refine the user experience.

Configuration on Ubuntu is super-simple. Here’s an example:

In /etc/network/fan:

# fan 241
241.0.0.0/8 172.16.3.0/16 dhcp

In /etc/network/interfaces:

iface eth0 static
address 172.16.3.4
netmask 255.255.0.0
up fanctl up 241.0.0.0/8 172.16.3.4/16
down fanctl down 241.0.0.0/8 172.16.3.4/16

This will map 250 addresses on 241.0.0.0/8 to your 172.16.0.0/16 hosts.

Docker, LXD and Juju integration is just as easy. For docker, edit /etc/default/docker.io, adding:

DOCKER_OPTS=”-d -b fan-10-3-4 –mtu=1480 –iptables=false”

You must then restart docker.io:

sudo service docker.io restart

At this point, a Docker instance started via, e.g.,

docker run -it ubuntu:latest

will be run within the specified fan overlay network.

Enjoy!

25 Jun 17:17

Os fundamentos da segurança de APIs

by Kleber Bacili

As APIs estão por toda parte. Com o “boom” das estratégias digitais em mobilidade, cloud computing, mídias sociais e os dispositivos inteligentes da Internet das Coisas, muitas empresas estão desenhando e expondo REST APIs – desde jovens startups até grandes empresas.

E temos que considerar que 2014 foi o ano em que o assunto “segurança” esteve nos holofotes – desde a Sony Pictures e a Jennifer Lawrence (que nada tem a ver com APIs) até casos como o da Tesla Motors, Snapchat e Bitly, em que vulnerabilidades nas APIs os levaram para os destaques dos portais de tecnologia e segurança da informação.

Mas como, então, sua empresa que já expõe ou pretende expor APIs pode se preparar para evitar que dados sigilosos de usuários possam cair em mãos erradas? É o que o restante deste texto aborda.

Antes de qualquer coisa, é importante determinar o nível de criticidade e o risco ao qual sua API está exposta. Por exemplo, se os aplicativos que consomem sua API forem apenas apps internos, ou seja, desenvolvidos por sua própria empresa, o nível de risco é bem mais baixo do que quando a API possui centenas de apps externos desenvolvidos por outras empresas ou pela comunidade. Outros elementos que também devem ser considerados são: os dados que a API manipula são relacionados ao usuário e são informações sensíveis? A API permite operações que afetam os dados de forma severa (como remoção em bulk etc.)?

Dependendo da sua resposta a esses questionamentos, você poderá saber com mais precisão o risco de se negligenciar questões de segurança. Sugerimos que faça uma classificação de criticidade para embasar suas decisões de design.

api-1

Bom, mas partindo do pressuposto que sua API requer a adição de certo nível de segurança, agrupamos os 5 principais atributos, bem como as ameaças, vulnerabilidades e dicas de como mitigar os principais riscos.

api-2

1. Autenticação e autorização

Primeira e principal preocupação relacionada à exposição de APIs. Sempre! Você é realmente quem diz ser? Você tem acesso a esse recurso? Estas são perguntas fundamentais. Evitar ataques de força bruta e roubo de credenciais são ameaças relacionadas à autenticação e autorização de APIs.

As alternativas de mitigação desses riscos vão desde uma simples autenticação Basic HTTP a padrões mais modernos e seguros, como OAuth2 e OpenID Connect.

OAuth2 está se firmando como principal forma de autorizar acesso a determinado recurso, especialmente quando o acesso deve ser concedido pelo próprio usuário. Gigantes digitais como Facebook, Google, Twitter, LinkedIn o adotaram.

Você já deve ter se deparado com uma tela de um dos serviços acima solicitando que você dê permissão para um determinado aplicativo. Pois é, trata-se de um OAuth2, onde o Facebook é o Authorization Server e o TripAdvisor é o Client Application. Nessa situação, eu, como dono dos dados (Resource Owner), estou concedendo acesso a um determinado escopo de informações para o Client Application que, a partir daquele momento, pode buscar informações em meu nome.

Importante destacar que essa pode não ser a melhor alternativa para a sua API, mas certamente é um padrão que vale a pena ser estudado/considerado.

Vale destacar também que, independentemente de qual seja o mecanismo de autenticação/autorização que você escolheu, valem as máximas de nunca salvar tokens em plain-text, não enviar senhas por e-mail e tomar cuidado com forward/redirect de requisições em redes desconhecidas.

2. Privacidade

Ataques como Man-in-the-middle e Network Eavesdropping podem revelar dados sensíveis dos seus usuários. Então, é importante atentar para algumas contramedidas que diminuam o risco de exposição desse tipo de informação.

Destaca-se a importância do uso do SSL/TLS e, em algumas situações, é até recomendável que você use um mecanismo adicional de criptografia. Além disso, arquivos de log são fontes preciosas de informações que não deveriam estar lá, então, sempre faça o mascaramento de informações sensíveis, como números de cartão de crédito, informações de saúde etc.

3. Disponibilidade

As APIs estão acessíveis? O desempenho está satisfatório? Ataques distribuídos de negação de serviço (DDoS) estão entre os mais comuns. Então, como desenvolver as estruturas básicas para resistir bravamente?

A recomendação básica é instrumentalizar a monitoração do tráfego nas APIs, preferencialmente com alertas capazes de identificar comportamento malicioso.

Um recurso bastante útil em soluções de gerenciamento de APIs é a capacidade de limitar o uso dos apps por meio de controles de rate limiting (ou throttling).

4. Auditoria

E se um dos seus clientes alegar que ele não fez aquele conjunto de invocações à sua API e, portanto, não irá pagar o valor correspondente? Esse fenômeno é chamado de repudiação. Como evitá-lo?

Logs detalhados são a melhor alternativa. A capacidade de evidenciar o resumo das chamadas recebidas, bem como mostrar os detalhes dessas chamadas, é uma resposta bastante eficiente para a não-repudiação.

Alguns cuidados especiais devem envolver o fato de que arquivos de logs podem crescer (e muito!), e que esses arquivos nem sempre são fáceis de inspecionar/buscar. Uma alternativa interessante é deixar essa tarefa para ferramentas de API management.

5. Integridade

As APIs são como um canal de comunicação entre o mundo externo e seu backend. Permitir que recursos críticos sejam apagados requer sempre cautela. Alguns tipos de ataques como injeção de SQL, XML e JSON podem causar sérios danos.

A principal recomendação aqui é a busca pela redução da superfície de ataque, ou seja, nunca exponha recursos e operações que não precisem ser expostos. Parece óbvio, mas muitas empresas aplicam técnicas de geração automática de APIs a partir dos serviços e dados do backend. Essas técnicas, além de gerarem APIs com design deselegante e de difícil entendimento, por vezes podem abrir brechas indesejáveis.

Sim, realmente são muitos pontos a levar em consideração quando o assunto é segurança de APIs. Além de tudo isso, nunca é demais lembrar que o ser humano ainda é o elo mais fraco nessa corrente.

***

Texto publicado originalmente na Revista iMasters.

Mensagem do anunciante:

Quer expor APIs com segurança e impulsionar parcerias ? Conheça o API Management Suite da Sensedia

25 Jun 16:51

dizer

by Francisco Nunes

Há tanta suavidade em nada dizer e tudo entender.

(Fernando Pessoa)

Send to Kindle
25 Jun 16:27

Não é só você: a internet está sim ficando mais leeeenta

by Ronaldo Gogoni

slowpoke-001

Costumamos dizer que quem reclama de internet lenta não viveu na Era das Trevas, quando conexão discada era a regra e carregar uma simples imagem poderia levar horas. Só que há um pequeno fundo de verdade nessas queixas: de acordo com o HTTP Archive a rede está sim andando em marcha mais lenta, tudo porque os sites em geral… engordaram.

Não é culpa da sua conexão de dados, em geral os sites que todos acessamos estão cada vez mais cheios de coisas — de vídeos a GIFs a banners a imagens pesadas e outras coisas — e tudo isso precisa ser carregado no cache, logo páginas mais elaboradas vão demorar muito mais para abrirem.

snorlax

De acordo com a pesquisa realizada, o peso médio dos sites hoje é de 2,1 MB; o dobro do que era três anos atrás. Desse total 75% são imagens em alta resolução. Scripts vem em segundo com 16%, vídeos em terceiro com 10%.

Embora seja o principal motivo, não dá para culpa as imagens em alta qualidade pela engordada dos sites: o próprio avanço tecnológico também contribui para a lentidão. Hoje, com cada vez mais smartphones, tablets e smartwatches sendo utilizados é importante para o dono do site torna-lo responsivo, de modo que ele se encaixe em todos os formatos de dispositivos, para oferecer uma navegação personalizada e agradável. Isso requer código adicional e consequentemente, um tempo maior no carregamento.

Por fim há uma terceira causa: sites e serviços como o Google e Facebook, que coletam dados do usuário como forma de retornar ads, sugerir sites e outras coisas de forma personalizada. Tudo isso gera tráfego e consequentemente, uma maior lentidão na navegação geral. E isso sem mencionar encriptação, que adiciona uma camada adicional de complexidade e contribui para a redução da velocidade.

Se os sites em geral estão ficando mais pesados (ainda que isso represente um slowdown pequeno), o que fazer? Os administradores devem levar em conta o tempo que as páginas levarão para carregar junto de outros fatores para manter as visitas. Se livrar de coisas desnecessárias como o Flash e migrar de vez para o HTML5 é um bom começo. Evitar banners, que irritam e muito é uma outra medida muito apreciada, além de maneirar nos ads. Tudo para melhorar um pouquinho a performance.

Fonte: CNN.

The post Não é só você: a internet está sim ficando mais leeeenta appeared first on Meio Bit.








22 Jun 22:10

poesia

by Francisco Nunes

Cesse de uma vez meu vão desejo
de que o poema sirva a todas as fomes.

(Adélia Prado)

Send to Kindle
22 Jun 22:09

BGP and the System of Trust that Runs the Internet Pt. 1

by Owen Lystrup

Editor’s note: This is part one of a two-part series on BGP.

The number of smart devices connecting to the Internet are reaching an unprecedented level. Estimates are predicting as many as 75 billion devices will come online by 2020, which means Internet traffic routing is going to get a lot more complex.

What most Internet users don’t know, but many are beginning to discover, is the entire framework that holds the Internet together can be quite fragile. In fact the system in charge of correctly routing Internet traffic is largely built on a collective trust, or as The Washington Post recently described it, an ‘honor code’ of the Internet.

The fact is we all rely on core protocols of the Internet like BGP (border gateway protocol) and DNS (domain name services) every day. They are a foundation of the Internet. Even companies that provide content on the Internet but don’t need BGP services directly, still rely on the service to get that content to their customers.

This two-part series will cover BGP, what it is, how it works, and what global moving parts are involved. Part two of this series, publishing next week, will cover the technical and security issues surrounding BGP, and why they often have a drastic effect on a global scale.

The Buried Superhighway
There is good reason behind portraying the Internet as a superhighway. Internet requests have a starting point (usually a device or computer) and a destination (like a website or app service). But the superhighway analogy is also apt because the Internet–despite its illusionary feeling of magic behind a box–is largely a physical thing, consisting of cables that run for hundreds of thousands of miles, many of them underground.

Submarine Cables

An interactive map of the submarine cable routes, from submarinecablemap.com

Pictured is a map of the submarine routes Internet cables take around the globe. They are literally physical cables that surface out of the ocean to connect all the countries of the world to one another. The other half of what makes the magic of the Internet work, are the various standards and protocols involved–the documented, collective agreement on how the Internet and its protocols should function, and the provider companies who pledge to make them work the way they should. The resulting covenants between Internet providers, are what keep the entire wheel of the Internet churning. And BGP plays a major role.

A common description of DNS (domain name services) is “the address book” of the internet. DNS looks up and resolves domains, like google(.)com, to their correct IP addresses, which are the actual desired destinations. If DNS is the address book that finds the destination, BGP is the system of freeway signs that show which routes can get there.

Just like roads and freeways, some routes are quick and direct, and some routes send traffic on misdirected tangents. BGP is the complex, interweaving system that gets Internet traffic where it needs to go, hopefully as efficiently as possible.

Peering: Good Neighbors Make Faster Internet
Andree Toonk, founder of BGPMon and manager of network engineering at OpenDNS, explained in an interview that the problems and outages the world has seen recently that involved BGP start with how the networking relationships between providers and businesses work.

The Internet as it is today consists largely of two types of relationships between businesses and ISPs, Toonk said. The first and more straightforward type of relationship is between providers and customers. In this scenario, customers–smaller regional ISPs and businesses like DropBox and OpenDNS–pay large providers–like AT&T and Level 3–to provide connectivity service for their users and customers. This type of relationship is formal, and can be costly depending on the providers and the details involved.

Peering is the second type of relationship, Toonk says, and it brings a few unique benefits. If a small local ISP wants to connect its customers to Facebook, for example, and doesn’t want to pay the large ISP acting as the middleman, the smaller ISP can connect using a peering relationship. Getting to Facebook is much easier done when there is a direct connection, and it will usually have less latency. And, Toonk says, one of the great benefits in a peering relationship is usually much more cost effective.

Internet Exchanges Map

A map of Internet exchange locations from datacentermap.com

These peering relationships are typically established at an Internet exchange (IX). They are pretty much exactly what they sound like, a central location where a large number of ISPs, businesses, and content providers connect to one another physically. Exchanges exist all over the globe, and they allow a more direct way of connecting end users to the Internet and its bounty of sites and services.

These relationships are at the core of how companies and Internet providers connect to one another globally. But, as Toonk explained, they can also be the source for huge routing and security issues. That is because the relationships keeping the Internet functioning, especially peering relationships, are where the “honor code” mentioned earlier comes into play.

Stay tuned for part two, which will explain how the honor code works, how BGP is becoming a new target for hackers, its involvement in some of the largest Internet outages ever seen, and the steps the industry is taking to correct the issues.

The post BGP and the System of Trust that Runs the Internet Pt. 1 appeared first on OpenDNS Blog.

22 Jun 19:05

Apt-get, Dpkg e Aptitude

by Maudy T. Pedrão

Análise contextual entre o Apt-get, Dpkg e Aptitude

Um breve histórico – por Ricardo Paulino

O termo APT (Advanced Packaging Tool), em nossa língua descrito como ferramenta de empacotamento avançada consiste no conjunto conjunto de comandos a serem usados pela distribuição linux debian e outras distribuições baseadas no debian, como é o caso do ubuntu para administrar pacotes do tipo DEB.

O APT faz parte de um projeto grande e os planos originais de seus criadores não poderiam deixar de pensar em uma interface gráfica que facilitasse as suas relações com o usuário final do produto. Na comunidade daqueles que “alimentam” o linux com projetos, programação e correções de problemas, grande parte de seus usuários e/ou desenvolvedores se preocupa em tornar seus programas mais capazes de serem usados por pessoas mais leigas.

O linux vem fazendo um percurso rápido até as casas da pessoas comuns, sem formação especial mas com necessidade de obter as mesmas características oferecidas por sistemas operacionais pagos em sistemas operacionais baseados no linux, ao alcance de todos e mantidos por uma comunidade imensa e fervorosa por deixar seu código mais funcional e livre de erros.

Iniciativas de empresas como a Canonical, fabricante da distribuição Ubuntu, de disponibilizar seu o software de foma gratuita, algo garantido pela licença GPL (Gnu Public License), faz que muitos de seus usuários comprem seus serviços de hospedagem em nuvem ou o suporte técnico além de vários outros serviços da empresa.

Essa forma de pensar, de forma colaborativa, de grande parte dos usuários de plataformas linux é que provavelmente trará um futuro mais promissor para pessoas que não disponibilizam de recursos financeiros suficientes para investir em sofwares caros como é o caso da grande maioria disponível no mercado.


APT

O APT possui as opções de busca de pacotes, listagem de detalhes de um pacote, instalação de um pacote, atualização da lista de pacotes do repositório de pacotes do sistema, verificação e atualização para a versão mais nova de pacotes, remoção de pacotes, remoção e instalação de pacotes mais novos.

Funções do APT:

  • list – lista pacotes baseado no nome do pacote
  • search – procura na nas descrições dos pacote pela <keyword> dada
  • show – mostra detalhes do pacote
  • update – atualiza a lista dos pacotes disponíveis no repositório do sistema (list)
  • install -instala pacotes
  • remove – remove pacotes
  • upgrade – atualiza o sistema instalando ou atualizando pacotes
  • full-upgrade – atualiza o sistema removendo , instalando ou atualizando os pacotes
  • edit-sources – edita o arquivo de informação sobre as fontes para pacotes

O APT realiza o processo de instalação, remoção, atualização, listagem de foma automática, de modo que quaisquer outros pacotes derivados que possam ser necessários sejam também baixados e instalados durante o processo de instalação de um programa.

Vamos rodar um exemplo para o uso do comando apt:

sudo apt update

A figura a seguir mostra a tela do terminal rodando o APT para atualizar a lista de pacotes disponíveis para instalação.

apt-get no terminal

Apt-get

O apt-get é baseado numa biblioteca que contém as aplicações principais para manipulação de pacotes, o apt, ele é o primeiro front-end — em linha de comando — que foi desenvolvido dentro do projeto debian. A figura abaixo mostra a excução de uma atualização da lista do repositório de pacotes do sistema.

Apt-get updateO apt-get é o comando fornecido pela distribuição linux debian que lista e instala e atualiza pacotes e dependências baseado na lista de fontes para os pacotes do repositório de pacotes. O arquivo que lista essas fontes é o arquivo sources.list, que está no diretório /etc/sources.list desta distribuição.

Com o apt-get também é possível instalar, remover, atualizar e listar pacotes, vamos listar as funções do apt-get:

  • update – atualiza a lista de pacotes disponíveis baseando-se nas fontes listadas no arquivo list-sources
  • upgrade – atualiza pacotes
  • install – instala novos pacotes
  • remove – remove pacotes
  • autoremove – remove automaticamente todos os pacotes não utilizados do sistema, útil após realizar várias atualizações pois deixa o sistema mais limpo
  • purge – remove pacotes e diretórios de configuração do pacote. Cuidado ao utilizar este comando sem critério pois serviços como o apache criam seu diretório de configuração /etc/apache2 e o purge irá removê-lo, depois, mesmo reinstalando o apache ele não cria de novo o diretório. Para criar novamente os arquivos de configuração do apache deverá instalar o pacote apache-data, que instala os arquivos comuns do apache.
  • source – faz o download dos arquivos de código-fonte para o pacote
  • build-dep – configura as dependências de compilação de pacotes de código-fonte
  • dist-upgrade – atualiza a distribuição, várias distribuições são geradas, ao longo do ano, entre elas 2 versões fechadas e outras intermediarias, se houver uma versão mais atual disponível o comando “apt-get dist-upgrad” atualizará o sistema com ela para você.
  • dselect-upgrade – segue as escolhas feitas no dselect, o deselect o um gerenciador de pacotes que funciona no modo texto, ele é mais antigo, ele era distribuido junto com o dpkg até junho de 2002.
  • clean – apaga pastas e diretórios obtidos por downlad durante a instalação de pacotes
  • autoclean – apaga pastas e diretórios obtidos por downlad durante a instalação de pacotes
  • check – verifica se existem dependências erradas
  • changelog – obtém e mostra o changelog de um pacote
  • download – obtém o pacote binário do pacote e descarrega no diretório atual

Aptitude

O aptitude mais um programa que facilita a vida do usuário ao coletar os pacotes disponíveis de acordo com o arquivo list.sources do sistema. Além de permitir ao usuário a facilidade para encontrar pacotes ele também instala, atualiza e remove pacotes da mesma forma que o apt-get.

Por ser um facilitador em coletar dados para o usuário dizemos que se trata de uma ferramenta front-end. Para ajudar o aptitude possui uma inteface gráfica e também pode ser utilizado através da linha de comando apenas digitando o comando aptitude.

Aptitude no Ubuntu

Acima podemos ver como é a tela do aptitude. É possível navegar no aptitude com as setas e instalar/remover/remover pacotes com a tecla “g”. É possível também atualizar a lista de pacotes do repositório com a tecla “u”.

Veremos um exemplo de como executar o aptitude pela linha de comando para atualizar a lista de pacotes disponíveis para instalação no repositório do sistema:

sudo aptitude update

aptitude

Para atualizar os pacotes instalados você poderá usar o comando:

sudo aptitude upgrade -y

O -y é a opção que faz com que o comando não peça confirmação.

aptitude

dpkg

O dpkg é fundamental para as distribuições debian pois ele é um programa de baixo nível (que lida de forma mais precisa, próxima com o hardware da máquina). Para que possam distinguir bem o APT e o RPM são ferramentas de alto nível com as quais temos mais facilidade de lidar.

Esse programa serve de base para as distribuições linux debian. Ele é usado para instalar e remover pacotes do sistema, bem como fornecer outras informações sobre esses pacotes. Os pacotes instalados pelo dpkg têm a extensão deb,

Ferramentas do dpkg são capazes empacotar e desempacotar pacotes, ler informações de pacotes, de mudanças nos pacotes em suas atualizações, podem cacular as dependências de certo pacote, enfim além de outras funcionalidades.

Lista de ferramentas dpkg:

  • dpkg-source empacota e desempacota os arquivos-fonte de um pacote debian.
  • dpkg-deb empacota e desempacota pacotes binários.
  • dpkg-gencontrol lê a informação de um certo pacote que tenha sido desempacotado do repositório de pacotes do debian, gera um arquivo deb binário e cria uma entrada para ele nos arquivos debian.
  • dpkg-shlibdeps calcula as dependências ocorridas com respeito a bibliotecas.
  • dpkg-genchanges lê a informação de um pacote desempacotado da árvore-fonte do Debian gerando uma construção de controle de arquivos (.changes).
  • dpkg-buildpackage é um script de controle que pode ser usado para construir um pacote automaticamente.
  • dpkg-distaddfile adiciona um arquivo nos arquivos Debian.
  • dpkg-parsechangelog lê os arquivos de mudanças (changelog) de um pacote desempacotado da árvore-fonte do Debian.

Como exemplo de utilização do dpkg instalaremos o pacote do programa bluefish, para isso vou fazer o download do programa através do comando na pasta pessoal:

sudo aptitude download bluefish

Agora que temos o pacote bluefish_2.2.6-2_amd64.deb iremos instalá-lo com o aptitude:

sudo dpkg -i bluefish_2.2.6-2_amd64.deb

A figura a seguir mostra o comando sendo executado no terminal do Ubuntu:

dkpg no linux

Espero que esse texto lhes seja útil!

fontes: todos os assuntos aqui tratados foram tirados de conhecimento formados em trabalhos e estudos diversos além de leituras em artigos disponíveis sobre o assunto no site wikipedia e com o comando man. O comando man seguido do nome do comando a ser pesquisado retorna um texto explicativo para ajuda.

Agora sabemos as diferenças entre o apt-get, o dpkg e o aptitude.

O post Apt-get, Dpkg e Aptitude apareceu primeiro em Ubuntu Dicas.

20 Jun 17:00

G ou J?

by Francisco Nunes

Dia desses, em Santo André (SP), topei com esta placa:

/Logista/? De onde tiraram isso? O autor da placa provavelmente pensou que um texto tão pequeno, tão simples, que qualquer um escreve, não precisaria de revisão. Errou feio. O autor esqueceu que as palavras que indicam “pessoa envolvida com” (para tentar uma definição bem ampla) em geral são compostas pelo substantivo de origem menos a vogal final mais a terminação ista. Assim:

  • Coro ⇒ corista
  • Arte ⇒ artista
  • Maratona ⇒ maratonista
  • Malabar ⇒ malabarista
  • Frente ⇒ frentista
  • (Conta) corrente ⇒ correntista
  • Periódico ⇒ periodicista
  • Dente ⇒ dentista
  • Marx ⇒ marxista
  • Comunismo ⇒ comunista
  • Jornal ⇒ jornalista
  • Governo ⇒ governista
  • Loja ⇒ lojista

Quando o substantivo de origem termina em ditongo, a última vogal é cortada e adiciona-se apenas sta.

  • Equilíbrio ⇒ equilibrista

Há outros casos, que acontecem mais raramente, mas todos eles respeitam o termo de origem. Então, de onde tiraram /logista/? Aqui não há como ter dúvida entre G ou J.

Beringela ou berinjela? G ou J?

O segundo erro feio é ainda mais inexplicável: diregente. Mais uma vez vemos que falta faz um revisor… Os substantivos e os adjetivos terminados em ente indicam, de modo geral, ente (pessoa ou coisa) que executa o verbo de origem do termo ou que tem o que é designado pelo substantivo de origem. Alguns exemplos:

  • Presidente ⇒ ente que preside
  • Paciente ⇒ ente que tem paciência
  • Gerente ⇒ ente que gere
  • Absorvente ⇒ ente que absorve
  • Doente ⇒ ente que tem doença
  • Conferente ⇒ ente que confere
  • Parente ⇒ ente que tem parentesco
  • Delinqüente ⇒ ente que delinqüe (sim, existe o verbo delinqüir)
  • Detergente ⇒ ente que deterge (sim, existe o verbo detergir)
  • Dirigente ⇒ ente que dirige

Assim como não existe /presedente/, não pode existir /diregente/. A menos que… Lembrei de uma coisa! Minha esposa tem um parente distante que diz, do alto de sua sabedoria: “Quem veve e direge tá sucetive de certas rebardaria”. Será que ele se mudou para Santo André e está pintando placas?

O post G ou J? apareceu primeiro em Que falta faz um revisor!.

18 Jun 14:53

Usando logs de acesso do servidor web como um sistema de armazenamento de banco de dados

by Mattias Geniar

Eu usei esse truque há alguns dias, quando lancei o Drupal EngineHack de detecção de sites, e ele está servindo ao seu propósito muito bem.

Meu caso de uso

O EngineHack verifica um site e informa ao usuário se ele foi hackeado ou não. Assim, para cada ferramenta em particular, quero registrar os resultados dessas verificações. Mais importante, eu queria fazer o registro de itens específicos:

  • O timestamp de cada verificação que foi realizada
  • A URL do site que foi verificado
  • Se o servidor Drupal foi comprometido ou não
  • Opcionalmente, o IP do site que efetuou a verificação, para o caso de abuso ou ataque DoS

Tradicionalmente, eu iria criar uma tabela em um banco de dados como MySQL ou um sistema de armazenamento simples por chave/valor como o MongoDB e armazenar os resultados obtidos lá. Mas eu não queria gastar muito tempo lidando com injeção de SQL, validação de dados etc.

E armazenar coisas dentro de uma tabela MySQL nem sempre é tão prático: eu não tinha uma interface gráfica, então tudo tinha de ser feito no terminal, via linha de comando. Criação de tabelas, inclusão de dados, consultas etc. Tudo soava como um monte de trabalho desnecessário para uma ferramenta tão simples.

Deve haver um jeito mais fácil, certo?

Logs de acesso como método de armazenamento

Tudo o que você faz em um navegador é registrado no servidor web. Cada timestamp, cada URL e todos os parâmetros GET. Eu posso usar isso para servir o meu propósito!

access_logs_everywhere

A maioria dos dados que eu queria registrar já estava presente nos logs do servidor. Eu tinha o timestamp e o IP de cada uma das verificações.

Tudo o que restou foi a URL do site Drupal que tinha sido verificado e o resultado: comprometido, sim ou não.

Resolvi incluir um pixel escondido na página de resultados. A URL foi assim.

<img src="/check_pixel.png?url=http://www.domain.tld&compromised=false"
     width="1px"
     height="1px"
/>

Ninguém percebe isso no browser. É o mesmo tipo de técnica que muitos rastreadores de conteúdo usam em ferramentas diversas para verificar as taxas de abertura de boletins informativos ou de acesso a determinados conteúdos.

Tudo que eu tinha que fazer agora era verificar meus logs de acesso para solicitações GET em busca daquele arquivo .png em especial e eu tinha tudo: o IP, o timestamp, o site que foi verificado e qual foi o resultado.

...
10.0.1.1 [28/Apr/2015:11:19:54] "GET /check_pixel.png?url=http://some.domain.tld&compromised=false HTTP/1.1" 200 901
10.0.1.1 [28/Apr/2015:11:20:05] "GET /check_pixel.png?url=http://www.domain.tld&compromised=true HTTP/1.1" 200 901 
...

Perfeito!

Consultando o conjunto de dados

Em longo prazo, criar uma instrução SQL é mais fácil do que isso. Mas, uma vez que eu faço tudo principalmente via linha de comando, isso parece mais natural para mim.

Quantos sites foram digitalizados?

$ grep 'check_pixel.png' scan_results.log | sort | uniq | wc -l
843

Note que eu não estou usando o comando grep -c para contar os registros, uma vez que alguns sites já foram verificados várias vezes, e eu quero apenas os valores exclusivos.

Quantos sites foram comprometidos?

$ grep 'compromised=true' scan_results.log | sort | uniq | wc -l
9

Quais sites foram verificados?

$ awk '{print $7}' scan_results.log | sort | uniq
...
/check_pixel.png?url=http://domain.tld&compromised=false
/check_pixel.png?url=http://otherdomain.Tld&compromised=false
...

Quais sites foram comprometidos?

$ awk '{print $7}' /var/www/enginehack.ma.ttias.be/results/scan_results.log | grep 'compromised=true' | sort | uniq
...
/check_pixel.png?url=http://domain.tld&compromised=true
/check_pixel.png?url=http://otherdomain.Tld&compromised=true
...

Eu tenho todos os resultados de que preciso, bem ali no terminal.

Logrotate

Uma desvantagem desse sistema é que ele não tem várias das propriedades ACID. O mais importante, pelo menos para mim, é a durabilidade.

Eu tenho o logrotate configurado para executar todos os logs do servidor toda noite e armazená-los durante 7 dias. Isso significaria meus logs de verificação também seriam excluídos depois de 7 dias, uma vez que os logs de acesso do servidor web são apagados após esse período.

Um script simples cuida disso.

#!/bin/bash
grep 'check_pixel.png' /path/to/access.log >> /path/to/permanent/logs/scan_results.log

Esse script é executado toda noite, antes do logrotate e leva os resultados do log atual para um arquivo permanente, com segurança, e os mantêm disponíveis para minhas consultas. Fácil.

Vantagens e desvantagens

Para mim, essa técnica funcionou perfeitamente. Meus benefícios:

  • Nenhum código complexo para armazenar dados em tabelas do MySQL é necessário
  • Resolvi a questão de concorrência de arquivos para registrar os resultados para o servidor web
  • Usei uma tecnologia comprovada para obter as solicitações de registro

Eu poderia conviver com as desvantagens também.

  • Não há consultas fáceis de dados, tudo acontece com os comandos grep / sed e awk diretamente no terminal em linha de comando
  • A consistência dos dados é resolvida por uma simples tarefa agendada

E aí estamos. Essa implementação levou 30 segundos para fazer e tem os mesmos resultados, pelo menos para mim, que seriam obtidos com um banco de dados relacional. Implementar uma solução MySQL teria tomado pelo menos 30 minutos ou mais, sem mencionar os problemas com injeção SQL, segurança, higienização de dados etc.

Fiquei feliz por não ter que fazer isso.

Advertências

Obviamente, em longo prazo, eu talvez tenha que armazenar os dados em uma tabela MySQL. Isso permitiria um gerenciamento muito melhor do sistema de armazenamento.

Esse #OpsHack funcionou para mim, porque meu conjunto de dados é simples. A quantidade de permutações possíveis dos meus dados é incrivelmente pequena. Assim que a complexidade dos dados aumenta, usar os logs de acesso para armazenar qualquer coisa passa a não ser mais uma opção.

Assim como o meu outro #OpsHack (usando zabbix para monitorar as apresentações HackerNews), esta foi a solução mais fácil para mim.

***

Mattias Geniar faz parte do time de colunistas internacionais do iMasters. A tradução do artigo é feita pela redação iMasters, com autorização do autor, e você pode acompanhar o artigo em inglês no https://ma.ttias.be/using-webserver-access-logs-as-a-database-storage-system/

17 Jun 19:45

Shaun M. Thomas: PG Phriday: 10 Ways to Ruin Performance: Out Of Order

There are a lot of database engines out there. As such, a developer or DBA will naturally have varying levels of experience with each, and some of this might conflict with how PGDB (PostgreSQL) operates. These kinds of embedded misunderstandings can cause potential issues by themselves, but in this particular case, corrective action is fairly simple.

So this week, I’d like to talk about indexes. Many people treat them as a “make query faster” button, and this often results in egregious misuse. Indexes take space, require CPU resources to maintain, and bring overhead that adversely affects INSERT and UPDATE performance. Most know these drawbacks and generally acknowledge that too many indexes can be detrimental. However, with some databases, even column order can make a drastic difference. PGDB is among these.

To illustrate the point, let’s make a simple test case of one-million records in an inventory tracking table of one thousand products over the course of about three years.

CREATE TABLE sys_inventory_snapshot
(
    product_id   SERIAL       NOT NULL,
    record_dt    TIMESTAMPTZ  NOT NULL,
    item_count   INT          NOT NULL,
    order_count  INT          NOT NULL
);
 
INSERT INTO sys_inventory_snapshot (
       product_id, item_count, order_count, record_dt
)
SELECT b.id, a.id, a.id,
       now() - (a.id || 'd')::INTERVAL
  FROM generate_series(1, 1000) a(id),
       generate_series(1, 1000) b(id);
 
ALTER TABLE sys_inventory_snapshot ADD CONSTRAINT pk_inventory_snapshot
      PRIMARY KEY (product_id, record_dt);

At first glance, this looks pretty good. If we want information based on date or product, it’s right there. Things are even better if we have both values available! The query plan is also encouraging:

EXPLAIN ANALYZE
SELECT *
  FROM sys_inventory_snapshot
 WHERE record_dt >= CURRENT_DATE - INTERVAL '1 day';
 
                            QUERY PLAN                             
--------------------------------------------------------------------
 Bitmap Heap Scan ON sys_inventory_snapshot
        (cost=22912.60..24880.07 ROWS=674 width=20)
        (actual TIME=106.051..106.530 ROWS=1000 loops=1)
   Recheck Cond: (record_dt >= (('now'::cstring)::DATE - '1 day'::INTERVAL))
   Heap Blocks: exact=7
   ->  Bitmap INDEX Scan ON pk_inventory_snapshot
         (cost=0.00..22912.43 ROWS=674 width=0)
         (actual TIME=106.027..106.027 ROWS=1000 loops=1)
         INDEX Cond: (record_dt >= (('now'::cstring)::DATE - '1 day'::INTERVAL))
 
 Planning TIME: 0.115 ms
 Execution TIME: 106.988 ms

Look at that! It’s using our date constraint to grab the most recent rows using the primary key for the table. That’s good, right?

Well, no. What’s actually happened here is somewhat esoteric, and the only real clue we have that something isn’t right, is the execution time. We just spent 100ms fetching 1000 records, which is downright offensive to an experienced DBA. Imagine this query in an application that’s executing it hundreds of times per second from multiple threads. In the database world, 100ms is basically forever. This table and query do not warrant such inexcusably bad performance.

So what happened? Buckets. Indexes take one value and point it to a bucket of other values. In the case of a composite index, one bucket value points to another bucket, which contains the values which satisfy both constraints. Now consider that record_dt is the second bucket. In order to ensure we get the most recent data for all products, we have to visit all of the top-level buckets before we can continue to the most recent date for each.

See the problem yet? Instead of simply jumping straight to the first applicable date value and retrieving the entire bucket, we have to visit 1000 buckets and then continue to 1000 smaller buckets. This is a fine access pattern if we had both the product_id and record_dt in the query, since that jumps straight to the values we want. But for everything else, it’s a non-ideal solution. It might be faster than a sequence scan if we’re lucky, but that’s not a guarantee. In some scenarios, it’s actually much slower.

PGDB veterans tend to solve this one of two ways:

  1. Reverse the column order of the index. If it turns out that 90% of queries use both columns, and 10% only use the second column, it’s better to flip them. The primary key in this case still fills its role, but without impacting performance of date searches.
  2. Add another index to represent the second column. This happens when the first column is actually used in exclusion or combination most of the time, but queries using only the second column are frequent enough to cause concern.

Because I’m lazy and don’t want to redefine the primary key, let’s take the second approach:

CREATE INDEX idx_inventory_snapshot_record_dt
    ON sys_inventory_snapshot (record_dt);
 
EXPLAIN ANALYZE
SELECT *
  FROM sys_inventory_snapshot
 WHERE record_dt >= CURRENT_DATE - INTERVAL '1 day';
 
                            QUERY PLAN                             
--------------------------------------------------------------------
 INDEX Scan USING idx_inventory_snapshot_record_dt
    ON sys_inventory_snapshot
       (cost=0.43..28.24 ROWS=674 width=20)
       (actual TIME=0.038..0.663 ROWS=1000 loops=1)
   INDEX Cond: (record_dt >= (('now'::cstring)::DATE - '1 day'::INTERVAL))
 
 Planning TIME: 0.238 ms
 Execution TIME: 1.087 ms

That’s… quite a difference. If you were unfamiliar with databases or PGDB, you might be surprised by this result. But the reality is quite clear: simply listing a column in an index does not magically improve performance of queries that reference it. Order matters. In addition, the further a column strays from the principal position, the worse the degradation becomes.

I’ve seen indexes with six columns, and then a baffled developer asks why his query is slow. Well, his query only used the fourth column in the list. At that point, reading the entire 30-million row table and filtering for desired results would have been faster. The planner tries to account for this, but sometimes statistics or settings lead it astray, and it performs an index scan and dutifully follows all those buckets down the chain to the fourth column. It happens.

Now that you know why, you’re armed to avoid contributing to the problem. Think about indexes before adding them. Consider existing indexes and queries against their parent table, and ensure that column order faithfully represents the real access pattern. It’s an important—and often missed—optimization technique.

As a side note, this is why serious companies have at least one DBA on staff. Designing table structures and optimizing queries are hard enough, but invisible killers like these are more prevalent than one might realize. An experienced database-driven application developer might be familiar with these kind of minutiae, but that’s a lot to expect. Not everyone reads database performance articles, or have encountered and addressed related problems.

Until next week!

16 Jun 18:44

A Ubuntização do Linux

by Maudy T. Pedrão

A Ubuntização do Linux

A Ubuntização do Linux e seus efeitos em nosso dia-a-dia. Algumas dúvidas sobre a influência do sistema no Linux.

por Lucas Zanella
http://cronicis.com/

Achar empresas que suportam Linux ou têm aplicações para a plataforma hoje em dia não é tão complicado como antes, mas há uma coisa que está tomando conta de tudo: o Ubuntu. O sistema está sendo ubuntizado, com grande maioria (senão todas) das empresas vendendo notebooks apenas com o SO roxo, isto entre as que o vendem.

A Ubuntização do Linux e seus efeitos

No Google Plus sigo por volta de dez comunidades sobre Linux e Ubuntu, e toda semana há aquela uma pessoa que levanta a questão: essa de o Ubuntu ficar cada vez mais popular é uma coisa ruim?

Ou será que isso transforma o Linux em algo mais… “visível”?

Sabemos que não é tão fácil imaginar um kernel, para um usuário comum, como é fácil imaginar o Windows ou o OS X, mas visualizar aquela interface unificada do Ubuntu não é difícil. Geralmente em programas de televisão encontramos um ou outro computador usando Linux, e em quase todos os casos se trata do Ubuntu.

Entro para a categoria daqueles que acreditam esta unificação do sistema ser algo bom, mas então lembro de distros como Arch Linux e Fedora. Agora, creio que essa ubuntização do Linux não afete seus derivados, como o Elementary OS, sistema que uso.

Posso, porém, imaginar a frustração de usuários do Fedora ao abrirem a página de download de uma página e verem um link para DEB, mas nenhum para RPM. Quando se pensa um pouco fora da caixa, transformar o Ubuntu no sistema padrão do Linux é o mesmo que transformar ele no nosso Windows. Ao procurarmos por bons programas, a grande maioria estará disponível apenas para ele.

A solução é até então inexistente, pois sei que é mais fácil para instalação um DEB do que um pacote de binários que funcionariam para todas as distros, até onde entendo do assunto. O lance é dar ao usuário burro (isto é, usuário sem conhecimento técnico, que não é um programador ou avançado) uma forma de realizar a instalação sem complicações, e creio que é nisso que nós, como um todo, devemos focar.

A melhor coisa que poderá acontecer para a plataforma do pinguim é uma certa unificação, moderada. Deixemos todos os projetos separados, como deve ser, mas criemos apenas uma maneira de instalação, segura e eficiente, de modo que seja possível para todos aproveitarem o sucesso que o Linux vem ganhando nos últimos tempos. Caso contrário, apenas terá o DEB, e todos sabemos disso. Antes trabalharmos juntos, como a comunidade que deveríamos ser, do que ficarmos dispersos e sem vantagens novamente.

Agora, não sei o quão viável isso é. Não sei nem mesmo se isso é possível, mas certamente seria um grande passo para o futuro do desenvolvimento de programas para Linux. As empresas nos olharão com outros olhos e talvez, apenas talvez, aquele um programa que o faz ficar nas Janelas venha para cá. Aí, meu caro, não haverá mais desculpas.

O que você acha sobre a ubuntização do Linux?

O post A Ubuntização do Linux apareceu primeiro em Ubuntu Dicas.

16 Jun 18:35

Sete exemplos de ótimo content marketing

by Cassio Politi

Este artigo foi publicado em 11/06/2015. Por ter sido considerado um dos melhores artigos de 2015, foi republicado hoje.

Content marketing é um método repleto de técnicas, conceitos e diferentes formas de se praticar. Para compreendê-lo e debatê-lo, selecionei sete exemplos, cada qual com o seu ponto forte.

1. Itaú

Um dos pilares do content marketing é a consistência do conteúdo. Uma das técnicas mais eficientes para se construir essa consistência é criar uma narrativa que descreva a missão da marca. E aí todo o conteúdo passa a contar trechos dessa narrativa. Essa técnica, chamada de storytelling de marca, é o tema central de um dos mais importantes livros da área, o Epic Content Marketing, de autoria de Joe Pulizzi. Pois bem, o Itaú consegue fazer exatamente isso. Em todas as suas comunicações — site, redes sociais, YouTube etc —, o banco conta a mesma história, cujo enredo é mudar o mundo.

01

Se tiver interesse em se aprofundar no tema, leia e ouça a recente entrevista com o Eduardo Tracanella, superintendente de marketing do Itaú. Ele tem uma visão bem rica e estratégica sobre a prática de content marketing.

2. Prefeitura de Curitiba

Fazer comunicação em órgãos públicos costuma ser um desafio ainda maior do que em empresas privadas, uma vez que os objetivos não são tão claros e os processos internos muitas vezes são lentos e complicados. Mas nada que resista a uma excelente iniciativa. Comandada por Marcos Giovanella (leia e ouça a entrevista com ele), a equipe de comunicação da Prefeitura de Curitiba conseguiu humanizar a relação com a população, especialmente em sua conta no Facebook, ao mesclar prestação de serviço e bom humor. Resultado: a interação é aberta, sincera, plena de diálogo, com espaço reduzido para os baderneiros que pululam nas redes sociais. A Prefs, como a Prefeitura se refere a si própria, começa a inspirar e encorajar outras instituições públicas a seguir o mesmo caminho.

02

3. Content Marketing Institute (CMI)

Contrariando o ditado, em casa de ferreiro, o espeto é de ouro. A maior referência de content marketing do mundo é também um case de content maketing. Analisemos: o que é o CMI? É uma empresa de eventos e de consultoria sediada em Cleveland, em Ohio, nos Estados Unidos. Poderia fazer os esforços convencionais de venda de seus serviços. Em vez disso, transformou-se numa empresa de mídia, com diversos canais de comunicação que alcançam, educam e influenciam o público. Resultado: seu principal evento, o Content Marketing World, recebe 3 mil pessoas de 50 países todos os anos.

03

4. McDonald’s no Canadá

Uma das regras essenciais de content marketing define que as marcas devem falar do que conhecem, e não do que vendem. Sendo esta uma regra, há exceções. O site Our Food Your Questions, do McDonald’s canadense, é uma delas. Foi lançado em 2012 e funciona assim: qualquer pessoa envia pelo site perguntas sobre os produtos da empresa. Têm especial valor as perguntas cabeludas, daquelas que colocam em xeque o fastfood. A equipe do McDonald’s tira as dúvidas em texto e, às vezes, em vídeo. Sim, ela toca nas feridas da empresa, e é aí que moram os benefícios. Há muito exagero em torno dos malefícios desse tipo de comida. Responder perguntas é uma forma de esclarecer que os lanches realmente não fazem tão bem quanto um prato de legumes e verduras, mas não são tão devastadores para a saúde quanto se diz. É um caso em que a realidade pode ser dura, mas é melhor do que os mitos. O formato peculiar do site, construído para atender a essa necessidade específica, é o que mais chama a atenção.

04

5. Ministério da Justiça

Você já ouviu falar do conceito de Youtility? Pois deveria. De forma bem resumida, podemos defini-lo como a prestação de serviços por uma marca, com o intuito de ajudar as pessoas a resolver seus problemas. O criador do conceito é o americano Jay Baer (leia alguns de seus textos aqui, na Tracto), fundador do site Convince & Convert e autor do livro Youtility, um best-seller nos Estados Unidos. Pois bem, no Brasil há ótimas iniciativas. Uma das mais interessantes é o aplicativo mobile Sinesp Cidadão, criado pelo Ministério da Justiça, sobre o qual já escrevemos no ano passado. Por ele, qualquer cidadão consegue saber se um carro é roubado apenas digitando a placa. E consegue descobrir se há mandado de prisão expedido para uma pessoa digitando apenas CPF e filiação. Um serviço e tanto para situações como a compra de um carro usado, a suspeita de um motorista à sua frente, a contratação de uma pessoa e assim por diante.

05

6. Oracle

Aquisição de clientes é um desafio para 68% das empresas B2B — aquelas que vendem para outras empresas — no Brasil e para 71% das B2B nos Estados Unidos e no Canadá. Para esse perfil de empresas, a construção de um mailing segmentado é fator-chave de sucesso. A Oracle nos Estados Unidos usa diversos canais para reforçar a busca por novos cadastros, que são a porta de entrada de um funil de vendas. O funil é normalmente gerenciado por ferramentas de automação de marketing (ou inbound marketing), uma das tantas opções que existem dentro do universo de content marketing. Perceba que boa parte das publicações em redes sociais aponta para um ambiente em que se gere cadastro do público — profissionais e empresas de TI —, como e-books, webinars e afins. É tudo uma questão de foco.

06

7. RedBull

Guardei para o fim o melhor exemplo. Quando, em consultorias, palestras ou aulas, me pedem para citar um — apenas um — exemplo de content marketing, não hesito: RedBull. A empresa que vende bebidas energéticas é o mais espetacular exemplo de produção de conteúdo com alma. A verdade da marca está presente em cada ação, como quando, em 2012, o austríaco Felix Baumgartner pulou de paraquedas da estratosfera numa ação da RedBull. Tudo para abastecer o canal RedBull TV e, de quebra, arrematar uma boa mídia espontânea. A ação está no DNA da marca, e é isso que rege toda a sua comunicação.

07

Eu poderia citar muitos outros exemplos estrangeiros (como Lego, MailChimp, Disney Park Blogs, My Starbuck Idea, The Ice Cream Journal, River Pools & SPA), ou brasileiros (Mundo Verde, Palácio do Planalto no SlideShare, Johnson’s Baby Brasil, Scup), mas preferi me ater a estes sete por enquanto. Os outros ficam para uma segunda rodada. Até lá!

14 Jun 17:25

Gotas de orvalho (2)

by Francisco Nunes
O sustento ao nascer do dia

Eu vindico o santo direito de desapontar os homens a fim de evitar desapontar Deus.

(A. W. Tozer)

Deus escreve com uma pena que nunca borra, fala com uma língua que nunca erra, age com uma mão que nunca falha.

(C. H. Spurgeon)

Se você fosse preso por ser cristão, haveria provas suficientes para condená-lo?

(David Otis Fuller)

As melhores ações do homem natural são apenas pecados espetaculares.

(Agostinho)

Tentar ser feliz sem uma percepção da presença de Deus é como tentar ter um dia radiante sem o Sol.

(A. W. Tozer)

Send to Kindle

O post Gotas de orvalho (2) apareceu primeiro em Campos de Boaz.

14 Jun 10:36

Help users checkout faster with Autofill

by idogreen

People hate filling out web forms, especially on mobile devices. They can be slow and frustrating to complete and often contain multi-page steps and validation issues. This leads to high user drop-off and frustration. To help make things easier for users, browsers have long been able to autocomplete fields on behalf of the user. Chrome took this a step further in 2011 by introducing Autofill, which fills in entire forms based on a user’s Autofill profile.

Starting in the next major version of Chrome (M43), we’re taking yet another step to help users fill out forms faster by expanding our support for credit cards and addresses in Google. This means that the same information users use to purchase things inside of the Google Play store are now available to them on websites. By using the standard autocomplete attributes, you can ensure your users’ happiness by helping Chrome autofill your checkout forms with 100% accuracy.

Autocomplete attributes are a way for you, the developer, to control how the browser should populate a given form field. For example, if you are expecting a street address you can hint to the browser that you are expecting it by using autocomplete="address-line1". This prevents the browser from incorrectly guessing form fields on your website which can result in a poor user experience.

We’ve found that by correctly using autocomplete attributes on your forms, users complete them up to 30% faster. And since autocomplete is part of the WHATWG HTML standard, we hope that other browsers will support it in the near future.

autofill git to show the power of fast and easy form filling

In the past, many developers would add autocomplete=”off” to their form fields to prevent the browser from performing any kind of autocomplete functionality. While Chrome will still respect this tag for autocomplete data, it will not respect it for autofill data. So when should you use autocomplete=”off”? One example is when you’ve implemented your own version of autocomplete for search. Another example is any form field where users will input and submit different kinds of information where it would not be useful to have the browser remember what was submitted previously.

The most common autocomplete attributes are shown in the table below and are documented in Web Fundamentals.

Common Attributes

Credit Card

name attribute

autocomplete attribute

ccname
cardnumber
cvc
ccmonth
ccyear
exp-date
card-type

cc-name
cc-number
cc-csc
cc-exp-month
cc-exp-year
cc-exp
cc-type

<label for="frmNameCC">Name on card</label>
<input name="ccname" id="frmNameCC" required placeholder="Full Name" autocomplete="cc-name">    

<label for="frmCCNum">Card Number</label>
<input name="cardnumber" id="frmCCNum" required autocomplete="cc-number">    

<label for="frmCCCVC">CVC</label>
<input name="cvc" id="frmCCCVC" required autocomplete="cc-csc"> 
  
<label for="frmCCExp">Expiry</label>
<input name="cc-exp" id="frmCCExp" required placeholder="MM-YYYY" autocomplete="cc-exp">

Name

name attribute

autocomplete attribute

name
fname
mname
lname

name (full name)
given-name (first name)
additional-name (middle name)
family-name (last name)

<label for="frmNameA">Name</label>
<input name="name" id="frmNameA" placeholder="Full name" required autocomplete="name">

Email

name attribute

autocomplete attribute

email

email

<label for="frmEmailA">Email</label>
<input type="email" name="email" id="frmEmailA" placeholder="name@example.com" required autocomplete="email">

<label for="frmEmailC">Confirm Email</label>
<input type="email" name="emailC" id="frmEmailC" placeholder="name@example.com" required autocomplete="email">

Address

name attribute

autocomplete attribute

address
city
region
province
state
zip
zip2
postal
country

For one address input: street-address
For two address inputs: address-line1 , address-line2
address-level1 (state or province)
address-level2 (city)
postal-code (zip code)
country

<label for="frmAddressS">Address</label>
<input name="ship-address" required id="frmAddressS" placeholder="123 Any Street" autocomplete="shipping street-address">

<label for="frmCityS">City</label>
<input name="ship-city" required id="frmCityS" placeholder="New York" autocomplete="shipping address-level2">

<label for="frmStateS">State</label>
<input name="ship-state" required id="frmStateS" placeholder="NY" autocomplete="shipping address-level1">

<label for="frmZipS">Zip</label>
<input name="ship-zip" required id="frmZipS" placeholder="10011" autocomplete="shipping postal-code">

<label for="frmCountryS">Country</label>
<input name="ship-country" required id="frmCountryS" placeholder="USA" autocomplete="shipping country">

Phone

name attribute

autocomplete attribute

phone
mobile
country-code
area-code
exchange
suffix
ext

tel

<label for="frmPhoneNumA">Phone</label>
<input type="tel" name="phone" id="frmPhoneNumA" placeholder="+1-650-450-1212" required autocomplete="tel">

The autocomplete attributes can be accompanied with a section name, such as:

  • shipping - given-name
  • billing - street-address

It is recommended because it will make your markup easier to parse and understand. The browser will autofill different sections separately and not as a continuous form.

An example of a payment form

<label for="frmNameCC">Name on card</label>
<input name="ccname" id="frmNameCC" required placeholder="Full Name" autocomplete="cc-name">

<label for="frmCCNum">Card Number</label>
<input name="cardnumber" id="frmCCNum" required autocomplete="cc-number">

<label for="frmCCCVC">CVC</label>
<input name="cvc" id="frmCCCVC" required autocomplete="cc-csc">
  
<label for="frmCCExp">Expiry</label>
<input name="cc-exp" id="frmCCExp" required placeholder="MM-YYYY" autocomplete="cc-exp">

Forms best practices

  1. Use _labels_on form inputs, and ensure they’re visible when the field is in focus. The label element provides direction to the user, telling them what information is needed in a form element. Each label is associated with an input element by placing it inside the label element. Applying labels to form elements also helps to improve the touch target size: the user can touch either the label or the input in order to place focus on the input element.
  2. Use placeholder to provide guidance about what you expect. The placeholder attribute provides a hint to the user about what’s expected in the input, typically by displaying the value as light text until the the user starts typing in the element. Placeholders disappear as soon as the user starts typing in an element, thus they are not a replacement for labels. They should be used as an aid to help guide users on the required format and content.

Demo

You can see it in action over at: greenido.github.io/Product-Site-101/form-cc-example.html
Or check the code: https://github.com/greenido/Product-Site-101

An example to a form that use autocomplete tags

11 Jun 21:09

Hubert 'depesz' Lubaczewski: Partitioning – what? why? how?

Recently I noticed that more and more cases that I deal with could use some partitioning. And while theoretically most people know about it, it's definitely not a very well-understood feature, and sometimes people are scared of it. So, I'll try to explain, to my best knowledge, what it is, why one would want to […]
11 Jun 21:09

Partitioning – what? why? how?

by depesz
Recently I noticed that more and more cases that I deal with could use some partitioning. And while theoretically most people know about it, it's definitely not a very well-understood feature, and sometimes people are scared of it. So, I'll try to explain, to my best knowledge, what it is, why one would want to […]
11 Jun 19:49

Como é simples mudar a cidade no site

by ProgramadorREAL
 

A internet da GVT está uma porcaria! Daí olha o que me aconteceu quando tentei ver a disponibilidade em uma das concorrentes…

//www.youtube.com/watch?v=PjaTA_XL6Uw

Em tela cheia dá pra ler melhor…

The post Como é simples mudar a cidade no site appeared first on Vida de Programador.

08 Jun 02:39

Roteadores são alvos de bankers brasileiros

by Augusto Campos

Enviado por Fernando Mercês (nandu88Θgmail·com):

“Uma técnica já utilizada por vírus há bastante tempo é substituir o endereço IP do servidor DNS da vítima por um malicioso, controlado pelo criador do vírus. Em geral para isso se precisava primeiro rodar um programa no computador da vítima, o que exigiria, no caso do Linux, baixar, dar permissão de execução e executar. No entanto, criminosos vêm criando scripts em JavaScript que alteram o servidor DNS diretamente no roteador wireless/ADSL da vítima. Ao embutir estes scripts em páginas HTML, cria-se uma poderosa ameaça multiplataforma, que afeta qualquer dispositivo conectado à rede, independente de sistema operacional, bastando que a vítima visualize uma página para a infecção ter sucesso.” [referência: blog.trendmicro.com]

O artigo "Roteadores são alvos de bankers brasileiros" foi originalmente publicado no site BR-Linux.org, de Augusto Campos.

08 Jun 02:11

TDC4Kids Especial para Crianças

by elcio

Olha que idéia genial:

O quê é o TDC4Kids

O TDC4Kids busca ensinar programação e um pouco de eletrônica para as novas gerações, de uma maneira mais descontraída, com bastante diversão e atividades.

Geralmente são realizados workshops que contam com a coordenação de grandes nomes do meio de TI, que também são excelentes pais e mães, onde temos como foco algum assunto específico de tecnologia, seja ele um meio de programação ou formas de modificações em um jogo bem bacana.

Se o seu filho gosta de computadores, jogos, brinquedos eletrônicos e é bem focado, não deixe-o de fora!

Parabéns à Globalcode pela ideia! Você pode assistir o TDC e levar seus filhos (ou sobrinhos) para aprender também!

Saiba mais no site do evento.

 

O artigo TDC4Kids Especial para Crianças apareceu primeiro no site da Visie: Visie.

05 Jun 20:26

Text editor rundown

by Eevee

As part of my experiment to monetize my personal brand, or however we’re describing this now, I have a milestone that lets a patron impose a blog topic of their choosing on me. What could possibly go wrong?

And so, this month, Russ brings us:

You should totally write about text editors.

I totally should. I mean, wait, no I shouldn’t. I haven’t seriously used a text editor other than Vim for years.

Thankfully this was a moderately vague request, so here’s what I’ve done: I’ve subjected myself to all these hip shiny text editors that I haven’t been bothering with and taken notes of my initial impressions. I only had a few hours to devote to each, so this won’t really be a fair comparison… but you know, life isn’t fair, so eat your peas and do your homework.

Sublime Text 3

Here is a list of all of the things I know about Sublime Text.

  1. It’s shareware.
  2. It does a neat file-opening thing when you press Ctrl-P, which is why we have ctrlp.vim.
  3. Something about multiple selections???

So, this should be fun.

Because this isn’t an open source project (gotta protect all those trade secrets buried in our text editor), it’s not in my package manager. So I went to their website to find a download link, an arcane ritual I have not had to partake in since time immemorial. My very first observation is that none of the download links use https, nor is there a checksum offered anywhere. This is a great start for an arbitrary binary that they want me to run and also hopefully give them money for. I ran it anyway because I follow 0xabad1dea on Twitter and I’m pretty sure that makes me a security expert.

I ran it, and it ran. It looked like a text editor, the empty canvas at once inviting yet paralyzing.

(This post contains no screenshots, because these things all look pretty much the same; imagine a lot of letters in a box, and you’re pretty much there.)

I vaguely recalled that Sublime has a file browser sidebar or something, so I hunted through the File menu. I tried “Open Folder” which sounded like it might do useful things related to editing multiple files in the same directory tree, so I tried that. And I got a file browser sidebar! Magic. Then I tried it a second time (because this project involves several subprojects), and it opened a new window, and that is an unforgiveable sin.

Then I noticed there’s a Project menu, but it sounded potentially invasive and IDE-like which put me right off. I have a deep aversion to editors that seek to manage “projects” for me — it reminds me of using C and C++ IDEs many years ago, where “project” meant “dozens and dozens of useless opaque junk files, vastly outnumbering your actual source files, which squirrel away all the important metadata so you have no hope of ever building your project from anything but our IDE, which by the way you will want to purchase an upgrade for next year.” I’m working on a Python thing, so much of that doesn’t apply, but the general aversion remains.

So we’re sticking with the open-folder thing. The sidebar is your classic drill-down file browser, and I’m immediately confused by its contents. I realize that I have a bunch of junk (.*.swp, *.pyc, and the like) ignored in both zsh’s and Vim’s tab completion, so it’s very rare that I actually see half of the files I’m now presented with. Seems odd that it doesn’t know out of the box to ignore some common junk files. Or, since I’m opening a folder, respect .gitignore or something? That’d be pretty slick. (And not without precedent — it’s half the allure of ag.)

This minor problem is compounded by my workaround for opening two subprojects: I open the parent directory instead, which is a virtualenv, so it contains a bunch of junk like lib and bin that I will almost certainly not want to edit.

Anyway, let’s try editing a file. There’s no built-in Sass syntax, which is a little surprising. There’s also no built-in Mako syntax, which is less surprising but still annoying. I also discover that the list of known syntaxes includes a submenu “Python”, under which is a single choice, “Python”. Curious.

I’d intended to use each editor vanilla (especially since I don’t have time to try out dozens of packages for each), but understanding syntax is kind of a big deal in text editors, so I went off to hunt for some.

I found a Mako syntax package, but its install instructions were very terse, appeared to be for TextMate, and also didn’t actually work. I ended up finding a third-party package manager, Package Control, that seemed to be well-respected. That had a oneliner to paste into Sublime (which is, I suppose, one level above piping curl into bash), but it did get itself installed. The UI was almost entirely built out of the command palette, Sublime’s version of ex mode, so I still felt like I had no idea what I was doing. I went to browse packages, which just sent me to their website, which nowhere mentioned how to actually install anything. Turns out that once you’ve found the package you want, you go back to Sublime and there’s a separate “install packages” command in the Package Control menu which (again using the command palette) lets you just type the name of a package.

None of this is really important and none of it has anything to do with Sublime itself, but I was in a hurry and largely felt lost the whole time, for whatever that’s worth.

Anyway, I got the Mako package installed, and then discovered that installing it manually had worked in the first place, but I had to reopen the file or restart Sublime or something, so Package Control was a completely irrelevant detour. Whoops. I also learn along the way that Sublime reopens my previous files when I start it, which seems nice on the surface, but would surely be less nice if I were working on more than one thing at a time? Not sure how it works.

I go to edit some Mako and immediately discover that the syntax doesn’t recognize <%! ... %> blocks. Mako only has maybe four kinds of syntax, so it’s surprising that one of them would be missed. I’m also under the impression that Sublime is at least partly powered by Python — there are Python files in the Sublime tarball, and the Package Control oneliner was Python — so it’s extra surprising that it doesn’t correctly support one of Python’s most popular template languages.

I observe while using Sublime that it is, indeed, quite fast — the Ctrl-P “open a file by mashing parts of its name” launcher thing never slows for even an instant, and even shows the currently-selected file, syntax highlighted and all, in the background as I type. A lot of Vim plugins are distinctly not-fast, which is weird since they ought to have strictly less work to do. I wish more Vim plugins were more fast.

I’m extremely used to the hierarchy in Vim: tabs are at the absolute top level, and you can (arbitrarily) split each tab into panes however you want. Sublime seems to be the opposite: you can pick one of a few fixed “layouts” which give you multiple panes, but each pane gets its own distinct tab row. I can’t figure out how to switch panes with the keyboard, and there’s no menu item to give me a hint, so I’m stuck clicking between files which is super annoying. I also come to realize very quickly that I rely heavily on using :sp to split a pane and browse around it “temporarily” in one half while my old cursor position remains visible in the other. I can’t do that now without using this heavy-handed “layout” thing, so I have to just resist the urge. Between that and not having Ctrl-O (jump to the cursor position before the last major jump) I feel lost in my own files.

If you type a paired symbol, like [ or ", Sublime will fill in the other one for you, ahead of the cursor. That’s fine, since if you aren’t used to the feature or don’t like it, you can just type the closing symbol and Sublime is smart enough not to insert a second one. That’s fine.

But in HTML files, typing </ fills in the entire most recently opened tag. The double-typing prevention no longer applies, I guess because it’s more than one character, and this immediately drives me up the wall. If I type </, Sublime fills in </section>, and if I keep typing the rest of the tag name because that’s what I want to put in the file, I end up with </section>section>. It means typing is no longer typing. I have to learn (or just guess) when to stop typing the actual characters I want to see on the screen, or else I’ll be typing extra garbage.

Even better: Mako-in-HTML files still do this, and the suggested tag is often wrong! Mako’s <%foo> tags aren’t recognized, and of course embedded logic might completely change the nesting of tags, so on multiple occasions I have to go out of my way to delete the wrong thing that Sublime injected into my file without asking. And, after this happens, there’s a completion popup for HTML attributes (even though this is a closing tag and my cursor is beyond the > anyway), so the down arrow and enter keys don’t work correctly.

I really really don’t like when a text editor interferes with writing text. It interrupts me when I’m trying to get a thought onto the screen, and forces me to waste time cleaning up its errant suggestions.

Thankfully, once I’m used to this, the rest of my editing passes without major incident.

I discover that when I select a whole word, Sublime helpfully outlines other occurrences of that word, and… I don’t know. I’m dimly aware that there’s a multiple-cursor thing that lets me overwrite every instance at once, but there’s no indication as to how I actually use it. Nothing in the Selection menu, nothing in the right-click menu. Why is it showing me this if I can’t do anything with it? The answer eventually reveals itself: “Quick find all” creates a true multiple selection. This is a little bizarre to me — clearly Sublime has already found every occurrence, so why would I think to ask it to search again?

I do get a little frustrated that I can’t easily delete a single line. Shift-Home, Delete leaves a blank line, so I need to type Ctrl-L, Delete (Ctrl-L is select line) which is a little awkward. In Vim this is a quick tap, dd.

vintage

At some point I mention to Twitter that I’m trying out Sublime, and a few people mention they’ve heard it has a vi(m?) mode, or something. Indeed it does, called “vintage”, and it’s the only built-in package.

I do not have high hopes for this. I’ve tried things with a “vi mode” before, and it usually comes down to a handful of the most basic keybindings and nothing more.

I spent fifteen minutes with Sublime’s Vintage. Things that didn’t work:

  • Ctrl-W doesn’t switch panes; it closes the current file.
  • There is no ex mode. : opens the command palette, but only :w and :e with no arguments are implemented. So no :%s///.
  • Visual line sort of exists, but is broken; the selection is lost if you go up one line, then down. At this point you’re back in command mode, but the modeline claims you’re still in visual line mode.
  • There is no visual block mode.
  • gq followed by a direction works, but gqq does not.
  • d↓ deletes the current line plus the part of the following line up to the cursor position, which is wrong — it’s supposed to delete two entire lines.

I’m pleased to discover that zz/zb/zt, marks, (automatic) folds, and % all seem to work, but this is basically useless to me if even deleting lines is buggy.

Atom

With a new day comes a new editor, so it was time to try Atom, the text editor GitHub created for some reason.

A disclaimer: I’ve always thought Atom sounded ridiculous, so I might have a teeny bias towards making fun of it. Sorry in advance!

Atom has a welcome screen, which is something of an improvement over Sublime. It calls itself a “hackable text editor for the 21st century”, where I suppose “hackable” means “we have never used Vim”, and “21st century” means “JavaScript”. (If you’re not familiar: Atom is built atop WebKit.)

It also mentions that they anonymously collect metrics, which I seem to recall means Google Analytics is baked into my text editor. Perhaps “21st century” actually means “needs an Internet connection”.

The welcome screen offers me a list of things I can do, and the first one is “open a project”, so it looks like I have no choice this time. Thankfully, “project” here seems to just mean “directory”. I get a familiar sidebar, with a familiar unnerving problem — it lists junk files as well. What’s extra confusing here is that there’s a preference for “ignored files”, and the default value lists .git amongst other things, yet .git still appears in the sidebar. To what, then, does this setting actually apply?

The welcome screen also starts out vertically split, with each pane having its own tab strip, so this is looking a whole lot like Sublime so far.

I open a file and it becomes glaringly obvious, after my recent font adventures, that Atom is not using my default monospace font! Apparently (warning: page is totally blank with noscript, because it’s the 21st century, which means JavaScript) the default is “Inconsolata, Monaco, Consolas, ‘Courier New’, Courier”. I have Inconsolata installed, so that’s what I get.

This is kind of annoying, and I interpret it as the first sign of the Web platform leaking through. A website can’t reasonably be expected to serve different default fonts per client OS, but local software generally can, and on Linux you should be using fontconfig’s generic “monospace”. Atom, though, is styled with CSS, so all it has is a font-family somewhere. Which doesn’t even include “monospace” as a fallback.

I briefly consider fixing this. After all, the welcome screen (still open in the right pane) says I can customize anything in this hackable text editor, and encourages me to “uncomment some of the examples or try your own”. So I click the button and get a completely empty stylesheet, along with zero indication of what elements are actually available to me, which is a fairly important feature when writing CSS.

I don’t really feel like wasting time researching the DOM of my text editor when I’m only going to use it for a few hours, so I give up and will just live with Inconsolata for now.

Relatedly, I notice that Atom tries, and largely fails, to use my native theme — active menus have the wrong color and an inappropriate border, and menu items use the wrong background color on hover. It’s wrong in the same way Chromium is wrong, but it’s a bit more obvious when there’s a menu bar.

I finally start doing some actual work. I find that Atom has the same selection keybindings as Sublime. This is starting to feel a lot like a clone of Sublime. I guess to delete two lines I need Ctrl-L, Shift-Down, Delete? This is so awkward. I think Sublime was the same. I also discover that Ctrl-L selects the current line; Ctrl-L, Shift-Down selects the current line plus the following line; Ctrl-L, Shift-Up selects absolutely nothing. What?

I type a capital C in a Python file, and Atom automatically suggests a single completion: the class keyword. What? Capital I similarly suggests if, yet typing Tru fails to suggest True! Later on I start to get completion suggestions of English words from within docstrings and comments, so I don’t really understand how this is supposed to work at all. Sometimes Atom only manages to come up with a completion by the time I’ve finished typing a word, at which point… I’ve already typed it, so what use is it to show me a menu containing only the word I just typed?

Admittedly I’m pretty harsh on magical automatic features like tabless completion, because they have a high upfront cost in the form of distraction — they flash crap on the screen, and often they take over important movement keys like up/down arrow too. (Even worse here: Atom only directs up/down arrow to the completion popup if there’s more than one suggestion, so I have to actually stop and examine the popup if I want to know if my keys will work!) So when these features just plain don’t work, even if it’s only 10% of the time, I’m paying this cost for nothing.

Sometimes, the cursor disappears. I don’t know why. It comes back if I type some more.

Again, of course, there’s no Mako syntax built in. There is syntax for Rails HTML, Mustache HTML, and Go HTML, which I suppose speaks volumes about the people who built Atom. I wonder why this Internet-enabled text editor from the 21st century doesn’t offer to download syntax for me when it doesn’t recognize a filetype.

There’s no keyboard shortcut for “save all”.

I can’t scroll beyond the end of the document, which got really annoying when Thunderbird new-email alerts popped up while I was trying to add to the end of a file. I don’t like typing on the last visible line anyway; I can’t tell whether I’m actually at the bottom or there’s something more that I might care about. I tried to work around this by mashing Enter a lot, which preserved my current indentation level for every single new line, so I had ten lines in a row that consisted of nothing but eight spaces. Suddenly I understand why so many projects are full of trailing whitespace.

The rest of my adventure passes without incident. It is, after all, a text editor, and it successfully edited some text.

But I walk away enlightened. Finally, I understand why Atom exists: so a bunch of nerds making six-digit salaries can weasel out of paying seventy bucks to register Sublime Text.

Yes, I’m making fun of Sublime for being closed-source and of Atom for being a clone of it. Life’s not fair. Go mow the lawn.

Emacs

Despite what you might think, I bear no ill will towards Emacs. I may think Atom is silly for technical reasons, but I don’t actually care what text editor you use. Just as long as it’s not, like, Wordpad.

I saved this for last because I knew it would be like trying to learn Vim from scratch again, and I’m only spending a few hours with it so I can’t possibly do it justice.

Right off the bat I’m lost in the weeds. This whole time I’d thought XEmacs was just the name of Emacs’s GUI (you know, X for X11) mode, like how GVim is graphical Vim. Much to my surprise, XEmacs turns out to be a fork dating back to the 80s, which has not had a stable release in over six years. XEmacs’s website has a page explaining the differences, which was written in 2001 and half-heartedly updated in 2008.

I guess I’ll use Emacs, then.

Sorry, I mean GNU Emacs. GNU/Emacs?

On first start, it looks rather a lot like GVim. Except it has GRAPHICS (for some reason), and a proportional font, and hyperlinks. I briefly fear Emacs is actually a Dreamweaver clone.

Emacs is even worse at obeying my theme than Atom was, and this time I have no explanation. GVim gets it right.

There’s a tutorial, which I guess I should probably follow. I’m relieved to find that the tutorial is in monospace.

These keybindings are baffling. Ctrl-G to abort a partial command? Why not Ctrl-C? I don’t even know what Ctrl-G does in a terminal.

Apparently Ctrl-V means “view next page”, which is a bit of a stretch. (Why not PgDn? I try it. It works.) The mneumonic falls apart entirely on Page 2, wherein I’m told that Alt-V means “view previous page”. (PgUp works.)

Oh, here we go.

You can also use the PageUp and PageDn keys to move by screenfuls, if your terminal has them, but you can edit more efficiently if you use C-v and M-v.

I don’t know what kind of Stretch Armstrong fingers the author of this document has, but touchtyping Alt-V is not what I’d call “efficient”.

You can use the arrow keys, but it’s more efficient to keep your hands in the standard position and use the commands C-p, C-b, C-f, and C-n.

Yes, it’s much more efficient to use four letters that are all over the place.

To be fair, I don’t home-row touchtype. But also, I don’t tend to rapidly switch back and forth between moving around and typing. Moving is reading, typing is writing. They feel fairly different to me. I even position my hands differently when I’m reading, with my right hand floating between the navigation keys and occasionally the mouse. You might say they are totally different, uh… modes.

Hmm. Moving the cursor off the bottom of the screen causes the next line to jump to the middle of the screen, and I find myself having to hunt for where the cursor ended up. To be fair, I use zz all the time in Vim; this is only frustrating in Emacs because I didn’t expect it, and there’s no highlight for the current line. It sucks for reading, though, where I want to scroll more text onto the screen before I’ve read all the way to the bottom, so my eye can stay locked on the same position in the text and I can keep reading without interruption. Later I learn that to do that I need something like Ctrl-U, 4, Ctrl-V.

Alt-F and Alt-B move between words, but again, Ctrl-<Arrow> works fine.

Very often Meta characters are used for operations related to the units defined by language (words, sentences, paragraphs), while Control characters operate on basic units that are independent of what you are editing (characters, lines, etc).

I literally only know two things so far, and one of them uses Ctrl to mean “down” and Alt to mean “up”.

You can also move the cursor with the arrow keys, if your terminal has arrow keys. We recommend learning C-b, C-f, C-n and C-p for three reasons. First, they work on all kinds of terminals.

If you are transported back to 1972, you will be all set to use Emacs.

To insert a Newline character, type <Return> (this is the key on the keyboard which is sometimes labeled “Enter”).

This documentation is targeted at people who know what “newline” means, but are not familiar with the enter key.

Reinsertion of killed text is called “yanking”.

No wonder Emacs and Vim are bitter rivals. They use the same word to mean opposite things!

Okay, enough of that. I’ll finally edit a file.

First I have to look up how to open a file, because I already forgot. Luckily the tutorial is still open.

Emacs supports Git out of the box and automatically tells me my current branch in the modeline, which is pretty nice.

I make some minor changes. I already forgot how to save a file. I consult the help for the help and muddle through several attempts at searching by command name, until I finally come up with Ctrl-X, Ctrl-S, which I probably should’ve guessed.

Honestly, this is a harrowing experience. I edit as conservatively as possible, much like when I was learning Vim, so I don’t have to worry about being stalled in the middle of a thought by wondering how to accomplish some trivial task. I don’t know if there are vertical splits, and don’t bother to look. There’s a menu bar here, but it seems more concerned with checking my email and playing Tetris than actually making the power of Emacs more accessible.

None of my readline knowledge is helpful here. Even Ctrl-W doesn’t do what I expect: it deletes to the last mark, or something, rather than deleting the previous word.

There is no built-in Mako mode, of course. I don’t even know where to look for one. I don’t try.

I feel oppressed, suffocated. It knows what I am, and what I am is a Vim user. I am not welcome here. I turn back, confounded and saddened. Emacs demands patience be sacrificed upon its altar, and I have none to give. I am defeated.

As I leave, Emacs delivers a parting shot:

Unprinted PostScript waiting; exit anyway? (yes or no)

I have no idea what I pressed to make this happen.

But there is a glimmer of hope. I know of one other terminal editor that shares Emacs’s aspirations of modelessness. I have used it before. Perhaps I can use it once again.

Nano

I’ve heard, apocryphally, that some actual human beings have used Nano to edit actual source code. I haven’t needed to use Nano myself for well over a decade, but I’m curious to see how it holds up. Let’s give it a whirl.

We’re going all out here. First, does Nano do syntax highlighting? (Does Nano do color?) I find that yes, it totally does, but you have to explicitly include them in your .nanorc. Weird! I’m also alarmed by this warning:

Note: Sometimes you might get a segmentation fault after you have edited your ~/.nanorc file.

Thankfully, this doesn’t happen. I create a .nanorc (with Nano!) that loads Python syntax.

Time to open a file. Nano has all its important keys listed helpfully at the bottom of the screen. Ctrl-O actually means “write out”, so Ctrl-R is “read”, even though in terminals Ctrl-R means search through history. I think this is because Ctrl-S is the terminal sequence for freezing output, maybe? But Emacs uses Ctrl-S just fine. I don’t know. Also, Ctrl-G means “get help”, probably because Ctrl-H is the backspace key.

Nano even has tab completion, though it’s the crappy kind where it only fills in a unique prefix and then shows you all the possibilities, and you have to mash Tab like three times to get that much. I successfully load a Python file.

It is not syntax-highlighted.

The top of the screen still says “New Buffer”. I feel a dawning dread. I press Ctrl-O experimentally, and Nano asks me for a filename. It seems Nano literally read in the contents of a file, but did not consider itself to be editing that file. I begin to fear I don’t understand Nano, either.

I exit and instead start Nano with the file as an argument. This seems to work, and I have glorious 4-bit color. Decorators aren’t colored, but I can’t tell if that’s deliberate or not. Comments are bold red, an interesting choice for something that I often want to gloss over.

I pause.

It’s been so long since I’ve actually edited any text that I don’t remember what I wanted to do in the first place.

While I mull that over, it seems Nano defaults to hard tabs, and that won’t do. Another .nanorc edit saves the day. Unfortunately, Nano isn’t clever enough to delete an entire indentation level at once when I press Backspace.

I make some minor edits. Nano doesn’t automatically preserve the indentation level on Enter. I perspire slightly.

Nano has the same scroll behavior as Emacs — moving off-screen recenters the cursor. I wonder who copied who, here.

I wonder if Nano has tab completion.

No.

Nano does highlight trailing spaces, though (in green…?), which gives it a point over Atom.

I browse around this file a bit. I might have wanted a different file, but it seems impossible to open a file in Nano.

I’m cold and tired of this experiment. I want to go home. Color is a cute novelty, but Nano is still terrible.

Vim

Vim is my usual editor, really my only editor, so I would be remiss to mention text editors and not discuss Vim.

I can’t tell you what it’s like to use Vim for the first time. Well, hm, I suppose I can, since I still remember — it’s pretty much like my experience with Emacs, except with Vim you have to learn “press i to type words” first. After that, they’re pretty much the same: ancient relics of immeasurable power that you must learn one agonizing keystroke at a time.

The good

Almost universally, I run Vim in a terminal inside tmux. I can then pick up whatever I was doing from my laptop, without having to even touch my desktop or plan in advance in any way. I can edit files on remote machines with exactly the same editor, and without having to dink around with something like sshfs. This is fantastic.

It’s fairly Unixy, in the good way — there are a lot of little composable parts. There’s the motion adjectives (which I still struggle to remember to use), sure, but it’s also got regexes and pipes and whatnot. I can make a lot of one-off edits to files right from a text editor, which I vastly prefer to awk.

Undo persists, if you set it up! That’s awesome and has saved my ass a couple times. I didn’t think to check any of the editors above for persistent undo; oops.

The plugin ecosystem is massive. I don’t use too many of them (here’s what I’ve got), but there’s a good selection of stuff that’s unintrusive and quietly useful.

I could go on. (Maybe. Christ, it’s just a text editor.) But you don’t want to hear why I like something. No, no, dear audience, I know why you came here. I know what you want.

Here you go.

The bad

Vim is fairly hostile to beginners, and not even for any good reason. (zsh has a similar problem.) There’s the problem of backwards compatibility, sure, but consider: if a default changed, all the existing users with massive .vimrcs are exactly the people most capable of dealing with it. But instead of putting the biggest burden on the experts, Vim puts it on beginners, who not only have to figure out how to use it, but also have to hunt down the dozen or so knobs they need to turn to make Vim actually worth using.

Some defaults don’t even make sense. Why is mouse support disabled (in Unix terminals) by default? What possible harm is there in supporting mouse input? That’s about as unobtrusive as it gets.

I don’t actually use a lot of Vim’s functionality; it’s easier for me to use visual block mode and mash down-arrow a couple times than to count lines. (I have relnumber on, in the hopes that it might encourage me, but it hasn’t yet helped.) I suppose that’s not necessarily bad. Vim has a big enough surface area that everyone will naturally find the bits they want to use, and that’s fine.

But I never learned to use netrw, and I went ages without realizing how much you could customize Vim’s filename input. I always forget to use ctrlp, too — because it choked on Vim’s massive source tree and I trained myself not to try it because it’d freeze Vim.

Vim has massive surface area, and not much discoverability. The only way to find a new way to do something is to get tired of it and go hunt down a better way to do it. (At which point you discover you could’ve been doing it with two keystrokes.) I don’t know if there’s anything to be done here, but it seems a shame that there is so much overwhelming depth that after a decade I still haven’t gotten around to learning all (or even most) of it.

The encoding story is kind of weird. If you want to edit something that’s not in your default encoding, you have to do something wacky like :e filename ++encoding, maybe, and then I’m actually not sure what happens when you save. There are a surprising number of settings related to this, one of which (iirc) controls Vim’s internal charset, which I don’t understand why you’d really want to change. I’ve basically resigned myself to only editing UTF-8, and the occasional binary file.

The regex language is pretty weird. \v makes it mostly like you’d expect, but there are still oddities like < and > for matching word boundaries or {-} for non-greedy repetition.

I had some hopes that NeoVim might be trying to solve some of this—

Arrow key support in all modes enabled by default (new users will need this is you wish to keep as many as possible, but I believe they will naturally transition to the home row when they learn how convenient it is, and veteran users will feel right at home without even touching the arrow keys anyways).

right then. I actually forgot that hjkl control movement in Vim. I really, truly forgot. I guess I’m not a “veteran user”.

The ugly

There is a vast ecosystem of plugins, but actually finding them is a nightmare; you basically have to rely on finding a blog post written by someone who’s already found them (presumably from someone else’s blog post). There’s a directory on the Vim website, but in my experience most of the interesting development nowadays just happens on GitHub. I’ve never found browsing the official plugin registry to be a joyous occasion, really.

Vim does ship with a ton of language support, but all those syntax files risk getting crufty. And if you want newer ones… where do you look? I’ve seen at least five different Python syntax definitions floating around, all seemingly forked from each other.

Vim’s syntax definitions are based on regexes and keywords, so you’re not going to get any semantic highlighting (like coloring variable names based on scope) without some very heavy lifting. After numerous upgrades to “fixed” Python syntax, I still get the “id” in row.id highlighted like it’s a built-in function name.

Vim has a lot of built-in programming functionality, but it tends to be very barebones without third-party support. For example, there are motions for operating on a paragraph (of plain text), or a braced block (in C)… but not an indented block, like you might have in Python or Haskell or Inform. Or, um, vimscript. There’s a plugin to add this… and a page on the disastrously messy Vim Tips wiki that has no fewer than four slightly different versions of the same thing.

(This is gonna be a recurring theme here: the Vim ecosystem just never feels polished. It may not be entirely fair to blame Vim for the problems of its third-party contributions, but Vim needs its third party contributions in order to not rot. I know package management is a Hard Problem, but somehow Vim seems to be the worst off of the ecosystems I’ve seen, even though it should surely have the people from all the other ecosystems working on it.)

Speaking of C: Vim has a set of built-in highlighting groups (“identifier”, “constant”, etc.), but they are pretty obviously aimed at C. So languages that are insufficiently similar to C have to make creative use of the groups, which often means that two languages will end up not even using the same color for keywords, because they both had a different idea of how to map those keywords to highlight groups.

Even the color schemes contain fun surprises — the one I use seemed great, until I tried using vimdiff, and discovered it had chosen to use blue and purple backgrounds that clash horribly with almost every other color in the theme.

Different languages even configure your indentation differently; for me, HTML is very insistent about keeping the cursor in what it thinks is the “right” place. Not nearly so much for Python.

Also, my comments auto-wrap at column 80 while I’m typing in Python, but not in Mako. gq doesn’t work correctly on Mako comments, either. But they’re still colored as comments. I don’t know why any of this is.

For the longest time, it seemed that the only tab-completion thing anyone used in Vim was ctags, which was designed for C (because of course it was) and involves running some command outside of Vim first to index all your code. Recently there have appeared some plugins that try to do actual smart tab completion, like python-mode. But python-mode has a teeny tiny bug where sometimes it will think your “project” is actually your entire home directory, so the moment you press Tab, Vim freezes for minutes while python-mode recursively scans every file in your home directory looking for things to index.

I used python-mode for a while and I have, by and large, trained myself not to press Tab so much any more, unless I really mean it. Now I use some other thing, which half the time works and the rest of the time just sorta gives up and tries to suggest keywords and builtins. Either way, sometimes it takes longer to produce results than I would’ve taken to just type the word myself. I assume there’s some way to make this all work, but I’ve yet to find it.

Vim itself is pretty sleek, but I’m frustrated with this recurring problem of plugins freezing it with mountains of blocking work. It happened with python-mode, it happened with ctrlp, I’m sure it happens with others. This is Unix, right? Can you not run a child process or something?

I’m reminded of yet another plugin quirk. There’s a neat thing, gitgutter, which shows which lines you’ve added or modified. It creates a temporary directory to do its work. The thing is, on my (Arch) system, temporary files are nuked after ten days. So if I leave a Vim session open, then come back to it later, I get a bunch of error messages complaining that the temporary directory no longer exists. But just creating the directory makes it stop complaining, so clearly the plugin still works even without that data. The maintainer blamed this on Vim, so it’s still a silly problem with a silly workaround, which never happens with any other plugin. Swell.

Oh, and Vim inserts garbage if I click beyond the ~256th column of my terminal. There’s a reason for this, and I forget what it was, and I could swear it was fixed, but it isn’t.

Yeah so

Everything is bad and computers are terrible.

I don’t have the time to learn Emacs — hell, I barely have the time to learn Vim. I don’t see the appeal of Atom. Sublime Text seems kinda slick, but I’m pretty attached to being able to edit things in a terminal, so I don’t think they’ll be getting seventy bucks from me anytime soon.

My only hope is that someday tpope will descend from the heavens and solve all of my problems for me.

And after all this, I haven’t made much progress at all on the thing I was actually trying to work on. Damn.

05 Jun 19:45

Hans-Juergen Schoenig: DROP TABLE: Killing shared_buffers

Tuning shared_buffers in PostgreSQL is a pretty fundamental thing to do when setting up a high-performance server. In most cases adding more memory speeds up things considerably. Many tests have shown exactly that. However, there are some corner cases, which are not commonly mentioned and which can cause significant performance issues in some very rare […]
31 May 18:55

Azure Premium Storage… Testes com SQLIO

by mcflyamorim

Fala galera, faz tempo eim?

Bom, semana passada fiz uns testes em um cliente acho que a informação vai ser útil pra vocês.

Esse é um cliente que sofria demais com a péssima performance dos discos do Azure, todo a sua infra-estrutura de banco de dados está em VMs.

Depois de aplicar várias técnicas para minimizar o custo e melhorar a performance das operações de I/O, finalmente o storage premium ficou disponível (só pra País de primeiro mundo, adivinha se tem no Brasil?…) para compra, e conseguimos migrar tudo para o novo storage. Porém ficávamos sempre com aquela dúvida, e ai, vai melhorar mesmo? Quantos %? Qual a diferença de performance dos discos? … Para responder essas nossas dúvidas e ter certeza de que o novo storage está melhor, fiz alguns testes com SQLIO e criei alguns gráficos.

Antes de te mostrar os gráficos, deixa eu mencionar algumas técnicas que usamos que ajudam a minimizar o I/O pra caso você tenha tenha tempo (a.k.a. money) de migrar para o novo storage que é claro, custa mais caro.

Segue uma lista de itens que você pode rever no seu ambiente para otimizar o I/O:

  • · Use minimum Standard Tier A2 for SQL Server VMs.
  • · Keep the storage account and SQL Server VM in the same region.
  • · Disable Azure geo-replication on the storage account.
  • · Avoid using operating system or temporary disks for database storage or logging.
  • · Avoid using Azure data disk caching options (caching policy = None).
  • · Stripe multiple Azure data disks to get increased IO throughput.
  • · Format with documented allocation sizes.
  • · Separate data and log file I/O paths to obtain dedicated IOPs for data and log.
  • · Enable database page compression.
  • · Enable instant file initialization for data files.
  • · Limit or disable autogrow on the database.
  • · Disable autoshrink on the database.
  • · Move all databases to data disks, including system databases.
  • · Move SQL Server error log and trace file directories to data disks.
  • · Apply SQL Server performance fixes.
  • · Setup default locations.
  • · Enable locked pages.
  • · Backup directly to blob storage.

Sorry o inglês, fiquei com preguiça de traduzir… ;P Peguei a lista acima do seguinte link: https://msdn.microsoft.com/en-us/library/azure/dn133149.aspx

Bom, se mesmo assim você não conseguir a performance desejada, então vai precisar migrar para os novos discos com premier. A performance foi realmente surpreendente e fez o que prometeu.

Seguem os gráficos que são bem auto-explicativos, em laranja servidor novo, em azul servidor velho:

clip_image002

IPOS foi lindo de ver… Conseguimos bater 15k por segundo, contra ridículos 1400 que estávamos executando no servidor antigo.

clip_image004

Como podemos ver, a latência ficou entre 1ms e 34ms o que é MUITO melhor que o tempo resposta de 33ms a 182ms nos discos velhos.

clip_image005

MBs por segundo também melhorou demais… Agora consigo ler até 252mbs por segundo, contra 47mb…

Espero que seja útil…

Abs.

Fabiano Amorim


31 May 18:44

Shaun M. Thomas: PG Phriday: 10 Ways to Ruin Performance: IN-Sanity

When working with a database, sometimes performance problems are both far more subtle, and much worse than a query itself might suggest. The topic of this week’s PGDB (PostgreSQL) performance killers article concerns the use of the IN clause, and how misusing it can catastrophically obliterate the database in mysterious ways.

To that end, we’ll use a slightly revised single-table test case since it’s served us pretty well so far:

DROP TABLE sys_order;
CREATE TABLE sys_order
(
    order_id     SERIAL       NOT NULL,
    product_id   INT          NOT NULL,
    item_count   INT          NOT NULL,
    order_dt     TIMESTAMPTZ  NOT NULL DEFAULT now()
);
 
INSERT INTO sys_order (product_id, item_count, order_dt)
SELECT (a.id % 100) + 1, (a.id % 100) + 1,
       now() - (id % 1000 || 'd')::INTERVAL
  FROM generate_series(1, 1000000) a(id);
 
ALTER TABLE sys_order ADD CONSTRAINT pk_order_order_id
      PRIMARY KEY (order_id);
 
CREATE INDEX idx_order_product_id
    ON sys_order (product_id);
 
CREATE INDEX idx_order_order_dt
    ON sys_order (order_dt);
 
ANALYZE sys_order;

As usual, my test system is a simple dual-CPU VM with 16GB of RAM and some mysterious storage allocation from a SAN. All settings are default, and the version of PostgreSQL is the latest release of the 9.4 branch. I always recommend using the latest version of PGDB when possible, otherwise there’s a risk of missing important planner improvements.

As it turns out in this particular story, the IN clause is actually pretty well known to most developers I’ve worked with. This isn’t some obtuse syntax that only experts have encountered, and it’s used regularly in applications and ORMs through the industry. It’s ubiquitous, and consequentially, extremely dangerous.

Why dangerous? Let’s examine a sanitized query I encountered in an actual running production system. Now, our test case is scaled down by a couple orders of magnitude, so the results won’t be as drastic as what I encountered. Still, the query below performs much worse than anything we’ve discussed so far:

EXPLAIN ANALYZE
SELECT * FROM sys_order
 WHERE order_id IN (
        SELECT DISTINCT order_id
          FROM sys_order
         WHERE product_id = 10
       )
 ORDER BY order_dt DESC
 LIMIT 30;
 
                             QUERY PLAN                             
--------------------------------------------------------------------
 LIMIT  (cost=27768.47..27768.55 ROWS=30 width=20)
        (actual TIME=1362.794..1362.840 ROWS=30 loops=1)
   ->  Sort  (cost=27768.47..27791.97 ROWS=9400 width=20)
             (actual TIME=1362.785..1362.801 ROWS=30 loops=1)
 
 [ Horrible ugly mess redacted ]
 
 Planning TIME: 0.699 ms
 Execution TIME: 1363.219 ms

What we’re looking at here, is the planner ripping itself to shreds trying to optimize a query with several problems:

  • A subquery containing the same table with no aggregates.
  • Use of DISTINCT on a primary-key column.
  • Ordering the results on the outside query.
  • Using the LIMIT on the outer query.

Taking these in order, it should be obvious that the subquery is pointless in this example. The inside query is essentially the same as the outside query, minus the ordering and result limit. There are a number of reasons this might happen. The IN clause is primarily used as a type of glue. Often, a developer or ORM will take a working query and embed it as a subquery unchanged. The justification is fairly simple: I’m interested in these how these records are related, and I already have this working query.

In most cases, IN can be simplified into some kind of JOIN, since that’s how databases tend to combine related data. By using IN and a subquery, the planner has to perform numerous unnecessary optimization steps in an attempt to reach the best plan. As the amount of complexity increases, so does the number of potential execution paths. How many elements from the inner query, for instance, can be collapsed into the outer one? What is the resource cost for each variant of doing so?

Then there’s the DISTINCT clause within the inner query. That sys_order table is not joined with anything, and there are no row multiplying functions. It’s not possible for more than one of the same primary key in the results. Yet there it is, making the planner do more work.

The last two are closely related. Since the outer query doesn’t add any new WHERE clauses, applying an order and limiting the results at that point, is simply inefficient. The database must first execute the inner query to find the relevant order_id values, and afterwards, throw away all but the top 30 results. The planner could have used the index on order_dt and read it backwards. Or it could have used the index on product_id and then ordered the results afterward, depending on which was more efficient based on statistics. Instead, it has to produce, and then subsequently discard, all data that matched the subquery.

Here’s what the query should have been:

EXPLAIN ANALYZE
SELECT *
  FROM sys_order
 WHERE product_id = 10
 ORDER BY order_dt DESC
 LIMIT 30;
 
                             QUERY PLAN                             
--------------------------------------------------------------------
 LIMIT  (cost=0.42..172.64 ROWS=30 width=20)
        (actual TIME=5.049..5.101 ROWS=30 loops=1)
   ->  INDEX Scan Backward USING idx_order_order_dt ON sys_order
           (cost=0.42..53960.42 ROWS=9400 width=20)
           (actual TIME=5.046..5.073 ROWS=30 loops=1)
         FILTER: (product_id = 10)
         ROWS Removed BY FILTER: 9000
 Planning TIME: 0.099 ms
 Execution TIME: 5.137 ms

Oh, look! There’s that backward index scan I mentioned. The row estimates are a bit off, and we’ll probably want to increase statistics and analyze to produce better values, but this is a speed improvement of over 250x. In a production system, even a few milliseconds can be a huge problem with enough throughput. Multiply that by 250, and the issue is upgraded to a catastrophe.

So how did this happen?

In this particular instance, it was the fault of Java Hibernate. An object for the inner query was passed to another object to flesh out the order detail, and the result almost crashed a production system. The fix was to make smarter use of Hibernate capabilities so it didn’t generate such a terrible query. Indeed, code refactors are probably something we should all consider doing more often in order to reduce accumulated technical debt.

Unfortunately, human-generated queries aren’t free from fault, either. It’s far too tempting to smash two queries together, than to rewrite them as a merged version using proper JOIN syntax. I’ve done it myself when in a hurry to check something. The difference is that I know better than to commit such a hack to a permanent location in our code tree. And the reason I don’t do that, is because I know the potential havoc such a query can wreak.

And now, so do you. By itself, IN is a wonderful tool. But its allure can bewitch and ultimately betray when it becomes a crutch. PGDB has a lot of powerful syntax potential, and it would be a shame to limit ourselves to the basics out of familiarity.

30 May 21:48

Amazon Route 53 e endereços HTTP como Proxies de Health Check

by Jeff Barr

O recurso Amazon Route 53 Health Checks oferece a possibilidade de verificar se endereços HTTP, HTTPS ou TCP estão plenamente acessíveis. Porém, há várias situações em que apenas um Health Check de conectividade não é o suficiente para determinar corretamente a saúde de uma aplicação. Nestes casos, a aplicação pode determinar sua própria saúde e expor um endereço específico para que o Route 53 verifique e execute o failover caso necessário. Neste artigo, veremos um exemplo usando Route 53 Health Checks para realizar o failover entre dois bancos de dados, um primário e outro secundário.

Determinando a saúde dos seus recursos

No exemplo deste artigo, usaremos pares de banco de dados, sendo que cada par possui um primário e outro secundário. Vamos considerar que o failover é necessário quando o banco primário não for capaz de responder à consultas. É importante ressaltar que os pares de bancos são independentes e sendo assim, um eventual failover de um dos pares não deve ter qualquer impacto sobre os outros.

Como sabemos, os tipos existentes de verificação do Route 53 não são realmente suficientes para determinar a saúde de um banco de dados. Um Health Check TCP poderia determinar se o banco de dados é alcançável, mas não se é capaz de responder a consultas. Além disso, gostaríamos de mudar para o banco secundário, não apenas se o primário é incapaz de responder a consultas, mas também de forma proativa se precisarmos realizar uma manutenção ou atualizações no primário. Então, como informar ao Route 53 sobre a saúde dos seus recursos?

Informando ao Route53

Uma vez que os bancos de dados em si não podem dar uma resposta adequada ao Health Check do Route 53, podemos criar um endereço HTTP para responder à requisições em nome dos bancos de dados. Este endereço atuará como um Health Proxy para o banco de dados, respondendo com status HTTP 200 quando o banco estiver saudável e HTTP 500 quando o banco de dados não estiver saudável. Nós podemos utilizar um único endereço HTTP para publicar a saúde de todos os pares de bancos de dados, e como cada endereço de Health Check do Route 53 pode conter URLs com caminhos específicos, podemos também atribuir um apontamento exclusivo para cada banco de dados.

Por exemplo, na Figura 1, vemos que o banco de dados primário usa o caminho “/DB1Primary”, enquanto o banco de dados secundário utiliza o caminho “/DB1Standby” no mesmo endereçamento IP e isso vai nos ajudar a economizar alguns recursos.

Nós também configuramos o failover para ocorrer quando há uma falha em um intervalo de dez segundos. Por padrão, esta configuração é de três falhas em trinta segundos, porém em nosso cenário já sabemos que apenas uma falha na verificação já é suficiente para deduzirmos que o banco não está saudável. Com esta configuração, o Route 53 irá detectar que o banco de dados está com problemas em aproximadamente 10 segundos.

Aumentando a disponibilidade

Até este momento, nós criamos Health Checks específicos para cada um dos nossos bancos de dados. Embora isso funcione bem para fornecer os estados ao Route 53, ele tem uma desvantagem que os controles tradicionais não possuem. Se o componente responsável em expor o endereço de verificação falhar, todas as verificações do Route 53 falharão também. Isso impediria a nossa estratégia de funcionar.

Portando, a primeira coisa a se fazer é expor múltiplos pontos de verificação para o Route 53. Nesta abordagem, todos os pontos de verificação devem fornecer o status dos mesmos recursos. Dessa forma, se um dos endereços HTTP não estiver disponível, ainda teremos outro para realizar o health check. Vamos, então, configurar uma verificação para cada par de banco de dados e endereço HTTP.

O diagrama abaixo mostra como cada componente que expõe o endereço HTTP fornece o status do banco primário e também do secundário. A linha em negrito no diagrama mostra como o estado do banco primário é fornecido pelos dois endereços HTTP ao Route 53.

 

Figura 1 – Diagrama dos componentes

Figura 1 – Diagrama dos componentes

Com dois endereços HTTP, vamos considerar que o banco de dados primário está saudável se ao menos um endereço HTTP retornar que está tudo bem. Isso fornecerá o comportamento desejado caso todos os pontos de validação HTTP estejam desativados.

Para configurar esse comportamento, usaremos uma configuração do Route 53 chamada Weighted Round Robin (WRR). Cada ponto de verificação de banco de dados terá um conjunto de WRR separado, sendo a ponderação para o primário configurada como 01 e para a secundário 02. Quando todas as verificações de saúde do banco de dados primário retornam que estão saudáveis, o Route 53 escolhe aleatoriamente um dos registros de peso 01. Uma vez que todos contêm o mesmo endereço IP do banco de dados primário, não importa qual deles é escolhido. Quando todas as verificações de saúde do banco de dados primário apresentarem falha, seus conjuntos de WRR de peso 01 não serão considerados e o Route 53 escolhe aleatoriamente um dos registros com peso 02. Mais uma vez, todos estes registros devolvem o mesmo endereço IP, de modo que não importa qual deles é escolhido. Finalmente, se todas as verificações primário e secundários retornarem falha, o Route 53 irá considerar todos os conjuntos de WRR e escolhe entre os registros primários, pois possuem o peso 01.

O diagrama abaixo mostra um exemplo de conjuntos WRR configurados para failover DNS de um único banco de dados.

Figura 2 – Configuração WRR para um banco de dados

Figura 2 – Configuração WRR para um banco de dados

Aplicações e tradeoffs

Enquanto este artigo tratou apenas do failover para banco de dados, esta mesma estratégia vale para vários outros tipos de recursos. Isto pode ser aplicado a quaisquer outros recursos que não podem ser facilmente verificados pelo TCP, HTTP, HTTPS ou health check tradicionais, tais como servidores de arquivos, servidores de email, etc. Também poderia ser aplicada para outros cenários, tais como mover o workload para outro ambiente enquanto se realiza uma nova implantação ou quando a taxa de erro para um serviço sobe acima de 5%.

Também vale a pena mencionar que existem algumas desvantagens para esta abordagem que pode torná-la menos útil para algumas aplicações. O maior deles é que nesta abordagem as verificações não fornecem um status sobre a conectividade do recurso final, e sim do endereço HTTP. Para o caso de uso neste artigo, este não é um problema pois os bancos são avaliados e usados por componentes na mesma região, logo uma conectividade global não seria um problema.

O outro tradeoff é ter que manter componentes adicionais para os endereços HTTP. Em nosso exemplo, temos vários pares de banco de dados para avaliar, portanto o custo de dois servidores HTTP serão relativamente pequenos. Se tivermos apenas alguns bancos teremos que avaliar o custo-benefício da solução levando em conta parâmetros de negócio.

***

Artigo escrito por Ari Dias e Glauber Gallego. 

Este artigo faz parte do AWSHUB, rede de profissionais AWS gerenciado pelo iMasters.

28 May 18:13

alegria

by Francisco Nunes

Refresca teu coração. Sofre, sofre depressa, que é para as alegrias novas poderem vir.

(Guimarães Rosa)

Send to Kindle