Há bastante tempo eu (lonefreak) e krateria temos batido cabeça tentando entender porque uma aplicação em Rails, que rodava tranquila com Mongrels estava com problemas de lentidão no Apache (em ambos os casos dentro de um FreeBSD. Hoje, enfim, encontramos a solução.

Ao que parece, todo o problema residia na forma como o FastCGI, módulo utilizado pelo Apache, estava tendo problemas para iniciar uma instância do módulo, estivesse ele em modo Dynamic, Static ou External. Depois de fuchar e mexer um bocado, acabamos topando com este tutorial, realmente muito útil e que sugere a utilização de outro módulo, o fcgid. E não é que funcionou mesmo?

E foi relativamente simples de resolver. Leve em consideração que já tínhamos aqui um ambiente estável rodando Rails no Apache, com FastCGI, apenas muito lento. Então as mudanças não foram tantas. Instalamos o pacote do fcgid pelo ports e não pelo gem (o que por si só pode salvar você de muita dor de cabeça) e usamos a biblioteca fcgi_handler, ao invés da fcgi (com ou sem rubygems), como indicado no tutorial.

O fcgid não foi muito comentado e há pouca documentação disponível, mas pareceu muito mais robusto e estável que o FastCGI. Além disso, nos livrou do problema de tentar o Rails com o LigHTTPD.

See ya

Essa é boa!

Chat com desenvolvedor de um dos principais sistemas da empresa:

dsv: “Cara, to com problema de conexão no banco de dados”
eu: “OK, me diz em que banco vc quer conectar e em qual localidade”
dsv: “O banco é o xxxxx e a localidade… deixa eu ver…bom, tenho o IP do servidor”
eu: “Blz, pode ser”
dsv: “Anota aí 127.0.0.1″

Lastimável! Nem quero imaginar o que temos embaixo do tapete…

Ao tentar subir um serviço no Windows, pode aparecer uma mensagem indicando que o serviço iniciou e parou, e que muitos serviços fazem isso por não terem tarefas a realizar naquele momento. Não se deixe enganar por esse engano estúpido de tratamento de erro do Windows.

Vá ao event log e procure pelo erro ao subir o serviço. Se encontrar algo desse tipo:

Service cannot be started. System.Configuration.ConfigurationErrorsException: Configuration system failed to initialize —> System.Configuration.ConfigurationErrorsException: Invalid character in the given encoding. Line 4, position 33. (C:\path\to\service\config.exe.config line 4) —> System.Xml.XmlException: Invalid character in the given encoding. Line 4, position 33.
at System.Xml.XmlTextReaderImpl.Throw(Exception e)
at System.Xml.XmlTextReaderImpl.Throw(String res, String arg)
at System.Xml.XmlTextReaderImpl.InvalidCharRecovery(Int32& bytesCount, Int32& charsCount)
at System.Xml.XmlTextReaderImpl.GetChars(Int32 maxCharsCount)
at System.Xml.XmlTextReaderImpl.ReadData()
at System.Xml.XmlTextReaderImpl.ParseCDataOrComment(XmlNodeType type, Int32& outStartPos, Int32& outEndPos)
at System.Xml.XmlTextReaderImpl.ParseCDataOrComment(XmlNodeType type)
at System.Xml.XmlTextReaderImpl.ParseComment()
at System.Xml.XmlTextReaderImpl.ParseElementContent()
at System.Xml.XmlTextReaderImpl…

Trata-se certamente do encoding do arquivo de configuração em questão (ou qualquer outro arquivo envolvido no processo). Talvez você tenha alterado o encoding acidentalmente ao editar o arquivo, ou então algum desenvolvedor já tenha repassado o artigo pra você com o encoding incorreto.

Enfim, basta que você altere o encoding do(s) arquivo(s) (nesse caso, utilizei o encoding UTF-8, que deve funcionar na maioria das vezes) e voilá.

Service started successfully.

Particularmente eu gosto de usar o ActiveState Komodo para esta tarefa, mas existem montes de aplicativos para se fazer isso.

See ya

Google App Engine — a developer tool that enables you to run your web applications on Google’s infrastructure. The goal is to make it easy to get started with a new web app, and then make it easy to scale when that app reaches the point where it’s receiving significant traffic and has millions of users.

Google App Engine gives you access to the same building blocks that Google uses for its own applications, making it easier to build an application that runs reliably, even under heavy load and with large amounts of data. The development environment includes the following features:

  • Dynamic webserving, with full support of common web technologies
  • Persistent storage (powered by Bigtable and GFS with queries, sorting, and transactions)
  • Automatic scaling and load balancing
  • Google APIs for authenticating users and sending email
  • Fully featured local development environment

Google App Engine packages these building blocks and takes care of the infrastructure stack, leaving you more time to focus on writing code and improving your application.

Today’s launch is a preview release — we’re by no means feature-complete, and we’re giving you early access because we really want your feedback. This preview of Google App Engine is available for the first 10,000 developers who sign up, and we plan to increase that number in near future.

During this preview period, applications are limited to 500MB of storage, 200M megacycles of CPU per day, and 10GB bandwidth per day. We expect most applications will be able to serve around 5 million pageviews per month. In the future, these limited quotas will remain free, and developers will be able to purchase additional resources as needed.

Chupinhado do Rlslog.net.
It is called the TeraDisk and it is really small, like a ordinary CD/DVD. But it’s really huge in terms of space. 1 TB (1000 GB). How can this be done? The process is easy (or not). All existing optical media record data on semitransparent layers. A regular CD has 1 layer and a Blu-Ray disk has up to 8. The reason nobody can add more layers on a regular CD/DVD/Blu-Ray disk is because when the light passes through these layers it becomes distorted and by the time it reaches the final layers it becomes almost impossible to read/write on the disk.

TeraDisk achieved the 1TB limit by using 200 layers, each storing 5GB of data. So basically the data support stay the same (TeraDisk will be made out of the same plexiglas like material used in other disks) but the write/read laser technology is completely new. They say it’s going to be cheap and it will be available for the public in 2010.

Forçar o download de um arquivo numa aplicação rails, ao invés de deixar o conteúdo ser carregado no navegador é bastante simples.

Tenho visto em vários fóruns uma centena de workarounds utilizando headers bem conhecidos, ou então um header um pouco mais obscuro, que a princípio daria mais velocidade e segurança ao download, mas que só funciona se você roda sua aplicação no Apache ou no Lighttpd, pois usa o mod_xsendfile.

Contudo, o próprio rails possui um método para lidar facilmente com isso, o send_file.

Neste caso eu mantive o caminho e mimetype da imagem em banco de dados após fazer o upload dela. Cobrirei o tópico upload em outro post mais pra frente. Assim, para utilizar o send_file, basta colocar em seu controller:



class MyController < ApplicationController
def downloadFile
# encontra os dados do arquivo procurado através de seu id
@file = myFile.find(params[:id])
# pega o nome do arquivo
filename = #{File.basename(@file.path)}
# pega o mimetype do arquivo
mimetype = @file.mimetype
# veja que o parâmetro disposition está com o valor attachment
send_file "#{RAILS_ROOT}/caminho/do/arquivo/" + filename,
:type => mimetype,
:disposition => 'attachment'
end
# outros métodos de sua classe controller
(...)
end

Com isso, o navegador não é redirecionado para outra página, removendo a necessidade de utilizar headers e o arquivo é enviado para download, já com mimetype reconhecido.

See ya

Released: March 10, 2008

Firefox 3 Beta 4 is a developer preview release of Mozilla’s next generation Firefox browser and is being made available for testing purposes only.

[Improved in Beta 4!] Firefox 3 Beta 4 includes more than 900 enhancements from the previous beta, including drastic improvements to performance and memory usage, as well as fixes for stability, platform enhancements and user interface improvements. Many of these improvements were based on community feedback from the previous beta.

http://www.mozilla.com/en-US/firefox/3.0b4/releasenotes/#download

Nunca mais vou dar fold antes do flop (repetir este mantra 1000x ao dia, em jejum)

nunca_faca_fold_cedo.JPG

maiden04-03-08.jpg

Por tempo demais adiei a criação desse blog. Tempo demais. Mas como terei ajuda e contribuição, então vamos lá.

Da minha parte o que você vai ver neste blog são descobertas e experimentos com programaçã, sysadmin, etc… Além das sempre pitorescas histórias de usuários que estariam melhores se estivessem mortos.

Se você sabe o que é sentir uma vontade incontinente de programar, de instalar aquele programa, de testar aquele SO, ou então já teve vontade de matar gerentes, coordenadores, desenvolvedores e usuários, seja muito bem vindo.

A idéia do /dev/beleza é ser um blog comunitário, aberto. Idéias e experimentos virão com o tempo. Meu antigo blog continua lá, abandonado. O conteúdo do /dev/beleza será bem diferente, pode apostar.

See ya