Friday, July 30, 2010

OAT plugins: Do it yourself! / Plugins para o OAT: Faça você mesmo!

This article is written in English and Portuguese
Este artigo está escrito em Inglês e Português


English version:

Some time ago, during a customer engagement, I felt the need to be able to show them if there were lock waiting sessions in their most busy system. Of course any old time Informix DBA will tell that onstat -k/K is able to provide this. But in their environment they needed this to be available to a broader audience than just the DBA team (who are the ones with database server command line access). So we decided to create a simple PHP script with Informix connection that showed it in a web page available in their Intranet. They're currently moving into using Open Admin Tool (OAT) and I though it would be nice to move that into OAT. Note that OAT already includes some reports that provide similar (although with less detail) information (session waiting report).
So I thought it would be nice to do it properly and create a plug-in. I searched around, specifically in OAT's home ( http://www.openadmintool.org ) and found a link to an article about creating plugins in OAT: http://www.ibm.com/developerworks/db2/library/techarticle/dm-0808vonbargen/
The author of this article is Erika Von Bargen, an IBM colleague, which is very active in the OAT specific IIUG mailing list. People who went to this year's IIUG conference possibly also know her since she was there presenting sessions about OAT.
Now... To tell you the complete truth, sometimes I'm very lazy (aren't we all at times?) when it comes to properly read documentation. So I just jumped into a terminal and started looking at an example plug-in provided with OAT. In a few minutes I had changed the query and I was seeing the information we were used to see in the customized web page. Obviously every message and column header was missing, the menus were wrong etc. But It was enough to become enthusiastic about this subject. I posted a few messages in OAT's mailing list, and had a quick feedback from Erika, which was a great help.
After the initial startup I decided to do it properly, and I read the article above, and it's a nice, clear and concise article. It's perfect to get you started.

So, after the initial "code, test, fix error, test....", instead of the "read, plan, code, test, fix..." I was ready to do it properly and I took some time at home to play with this. And I kept adding some features, some usability details and finally got to a point where I think I have a working plug-in. It has four options:
  1. List all the instance locks
    This shows information similar to onstat -K, but most of the information is immediately readable (meaning you don't have to query sysmaster to get the table names, and you don't have to run onstat -u | grep .... to get the session number.
  2. List locks with waiters
    This shows information on every lock that has a lock list. The information includes:
    - The owner username, session number, process id and client machine
    - The waiter username, session number, process id and client machine
    - The table/index in question, the time the lock was established and how long the wait is waiting
  3. List locks per table
    This shows information about locking for every active table in your system. The information includes the number of currently held locks, the number of lock requests made on the table, the number of lock waits, the number of deadlocks and the number of lock timeouts
  4. List locks per session
    This shows the number of currently held locks, the number of lock requests made by the session, the number of lock waits, the number of deadlocks and the number of lock timeouts
One of the great things about OAT is how easy we can localize our plug-ins. In this case, due to my linguistic limitations, I've only included the standard English messages and naturally the Portuguese ones. I'd be glad to add more, if people who can write in other languages (already used by OAT) could send me the translated messages. The number of words/phrases to translate is really short and to be honest I'm tempted to give some online translation a try... But I would prefer some user contributions, in case you find the plug-in useful....
Also, I'd love to receive feedback about bugs or improvements. I have a few ones on my mind, but it's always better to listen to others...

So, where is it? I've just upload it to IIUG software repository. It's the first time I do it, so I'm not sure how long will it take to become available
[UPDATE 31 Aug 2010]: It's already available on the IIUG repository .

If you want to check the aspect of it, before giving it a try, please see below some snapshots.

How stable is it? It wasn't tested on big systems. But all it does is query the sysmaster. So, the worst thing that could happen would be giving you some wrong information. It should not do any harm to your system. In any case treat this as a beta release for now. One thing that can happen is that the pages show all the information fetched by the queries. In large systems, with thousands of locks, sessions, or tables, this can translate into very big HTML pages... Be aware of this.
To the best of my knowledge the queries return proper results. The locks with waiters page is based on a query being used for a fairly long time. The other queries were created and tested in a very controlled environment, so admittedly it's possible that they don't cover some situations.

Every feedback is welcome. Although OAT already includes some functionality in this area, I think this will give you a more direct and condensed tool to monitor your database locking activity. As such I believe the plug-in can be useful and it certainly can be improved.


Versão portuguesa:


Há algum tempo atrás, durante um trabalho num cliente, senti a necessidade de lhes mostrar se tinham sessões à espera de locks no sistema mais utilizado. Claro que qualquer DBA Informix com alguma experiência dirá que o onstat -k/K é capaz de responder a esta necessidade. Mas no caso que refiro, era necessário que esta informação estivesse disponível para uma audiência mais alargada que apenas a equipa de DBAs (os únicos com acesso à linha de comando no servidor de base de dados).
Por isso, decidimos criar um script PHP, simples, com conexão ao Informix, que mostrasse a informação numa página Web disponível na Intranet da empresa. Actualmente estão a começar a usar o Open Admin Tool (OAT) e pareceu-me adequado colocar esta funcionalidade dentro da mesma ferramenta. Note-se que o OAT já fornece informaçao semelhante (embora com menos detalhe) no relatório de sessões em espera.
Assim pensei que seria bom fazer isto como deve ser e criar um plug-in. Procurei informação, especificamente no website do OAT ( http://www.openadmintool.org ) e encontrei uma ligação a um artigo sobre criação de plug-ins para o OAT: http://www.ibm.com/developerworks/db2/library/techarticle/dm-0808vonbargen/

A autora deste artigo é a Erika Von Bargen, uma colega da IBM, bastante activa na mailing list do OAT do IIUG. Quem teve oportunidade de estar na conferência do IIUG este ano também teve oportunidade de assistir a sessões apresentadas por ela, precisamente relacionadas com o OAT
Bom... Para ser franco, ocasionalmente sou bastante preguiçoso (não seremos todos de vez em quando?) quando toca a ler documentação. Por isso, abri uma sessão e comecei a estudar um exemplo de plug-in fornecido com o OAT. Em apenas alguns minutos, tinha mudado a query que lhe serve de base e estava a ver a informação a que estávamos habituados na página personalizada. Naturalmente, todas as mensagens e cabeçalhos de tabelas estavam errados ou em falta, os menus estavam errados etc. Mas foi o suficiente para me tornar um entusiasta do assunto. Coloquei algumas mensagens na mailing list do OAT e obtive respostas rápidas da Erika que foram uma grande ajuda.
Após o arranque inicial, decidi que devia fazer as coisas devidamente, e li o artigo mencionado acima, que é bom, claro e conciso. Ideal para quem quer começar com a tarefa de criar um plug-in.

Assim, após a abordagem inicial de "codificar, testar, corrigir erros, testar....", passei para a de "ler, planear, codificar, testar, corrigir....". Estava preparado para fazer isto como deve ser e disponibilizei algum tempo em casa para "brincar" com isto. E fui adicionando funcionalidades, detalhes para melhorar a usabilidade, e finalmente cheguei a um ponto onde julgo ter um plug-in que funciona.
Tem quatro opções:


  1. Listar os bloqueios na instância
    Isto mostra informação semelhante ao onstat -K, mas a maioria da informação é de leitura imediata (ou seja, não é necessário pesquisar na sysmaster para obter os nomes das tabelas, e não temos de correr um onstat -u | grep ... para obter o número da sessão
  2. Listar os bloqueios com fila de espera
    Isto mostra informação de cada bloqueio que tenha uma lista de espera. Esta informação incluí:
    - O dono do bloqueio, incluindo nome de utilizador, número de sessão, número de processo e a máquina cliente
    - Quem está à espera, incluíndo o nome de utilizador, número de sessão, número de processo e a máquina cliente
    - A tabela/indíce que tem o bloqueio, o instante em que o bloqueio foi estabelecido e há quanto tempo existe a espera
  3. Listar os bloqueios por tabela
    Isto mostra informação sobre os bloqueios para todas as tabelas activas do seu sistema.
    A informação incluí o número de bloqueios activos no momento, o número de pedidos de bloqueios feitos sobre a tabela, o número de esperas por bloqueios sobre a tabela, o número de deadlocks que envolveram a tabela, e o número de vezes que os tempos de espera por bloqueios expiraram
  4. Listar os bloqueios por sessão
    Isto mostra o número de bloqueios que cada sessão mantém activos, o número de pedidos de bloqueio feitos pelas sessões, o número de esperas por bloqueios, o número de deadlocks da sessão, e o número de tempos de espera por bloqueios expirados

Uma das coisas boas do OAT é a facilidade com que se pode localizar ou traduzir os nossos plug-ins. Devido às minhas limitações linguísticas, neste caso, o plug-in só incluí as mensagens em Ingês (standard) e naturalmente em Português. Gostaria de adicionar mais, caso quem escreva noutras línguas (das já usadas pelo OAT) me queira enviar as mensagens traduzidas. O número de palavras/frases a traduzir é realmente pequeno, e para ser honesto sinto-me tentado a experimentar os tradutores automáticos online. Mas seria preferível se alguém contribuísse caso considere o plug-in útil.

Adicionalmente, terei todo o gosto em receber comentários sobre bugs ou melhorias. Tenho algumas em mente, mas é sempre melhor escutar opiniões de outros...

Então, onde está o plug-in? Acabei de fazer o envio para o repositório de software do IIUG. É a primeira vez que o faço, e sinceramente não sei quanto tempo levará a ficar disponível.
[ACTUALIZAÇÂO 31 Aug 2010]: Já está disponível no repositório de software do IIUG.

Se desejar ver o aspecto do plug-in, antes de o testar, por favor veja as imagens abaixo.

Quão estável é o plug-in? Não foi testado em sistemas grandes. Mas tudo o que faz é pesquisar a sysmaster. Por isso, além de alguma possível informação errada não deverá causar qualquer problema nos seus sistemas. Em todo o caso trate isto como uma release beta por enquanto. Algo que pode acontecer é que as páginas mostram toda a informação obtida nas queries. Em sistemas grandes, com milhares de bloqueios, sessões ou tabelas, isto pode traduzir-se em páginas HTML muito grandes.... Tenha algum cuidado com isso.
Tanto quanto me apercebi, as pesquisas retornam resultados correctos. A lista de bloqueios com lista de espera baseia-se numa query que utilizo há bastante tempo. As outras pesquisas foram criadas e testadas num ambiente muito controlado, logo é possível que possam não prever algumas situações.

Todo o feedback será muito bem vindo. Apesar de o OAT já incluir alguma funcionalidade nesta área, julgo que este plug-in será uma ferramenta mais directa e condensada para monitorizar toda a actividade relacionada com bloqueios nas suas instâncias Informix. Como tal, acredito que o plug-in possa ser útil e certamente poderá ser melhorado.


Snapshots/Écrans:

















Lock List
Lista de bloqueios


















Lock waiters
Lista de bloqueios com fila de espera

















Locks per table
Bloqueios por tabela























Locks per session
Bloqueios por sessão

Chat with the Labs: Post End of Service Support Options and Upgrade Best practices / Opções de suporte após fim de serviço

This article is written in Portuguese and English
Este artigo está escrito em Português e Inglês


English Version:

Andrew Ford already announced this in his blog, so for the English version I'll just recommend that you check his article. Basically there will be a very important Chat with the labs session on August 26. For all the customers still in version 9.40 and v10, this may really make a difference.

Portuguese Version:

No dia 26 de Agosto decorrerá mais uma sessão "Chat with the labs" sobre o tema "opções de suporte após o fim de serviço e melhores prácticas para upgrades ou actualizações".
A IBM disponibiliza várias opções de suporte para clientes cujos productos tenham atingido o fim de serviço, e esse será o tema principal desta sessão.
O tema será mais relevante para clientes que estejam ainda a correr as versões 7.31 (sem suporte normal desde Setembro de 2008), a 9.40 (sem suporte normal desde Abril de 2008) e a 10 que deixará de ter suporte normal no próximo dia 30 de Setembro.
Na sessão serão também abordadas as melhores estratégias e prácticas para migrações da versão 10 para a 11.50.

Para assistir à sessão deverá registar-se em:

https://events.webdialogs.com/register.php?id=d6def198fd&l=en-US

Os slides deverão estar disponíveis antes da conferência em:

http://www.ibm.com/informix/labchats

Caso não lhe seja possível assistir em directo poderá obter os slides e mais tarde som. Caso o tema seja útil, e em caso de dúvida não deixe de contactar o seu representante IBM.

Sunday, July 25, 2010

A bug can undermine your troubleshooting / Como um bug pode minar a resolução de problemas

This article will be written in English and Portuguese.
Este artigo será escrito em Inglês e Português.

English version:

A few articles ago I tried to lecture on how to do a good troubleshooting. And I wrote that it all starts with an error or a bad behavior. When we have an error we should start from there. If we don't have it, it's harder.... But what about the situations when we have an error that says:

"No error message available"

Not good... I faced a situation on a customer where this happened. It's a Web application written in ASP using the windows driver (OleDB) and running on IIS. After an engine restart they started having an error that says:

No error message available, result code: E_UNEXPECTED(0x8000FFFF)
ErrorCode -2147418113

So, we had an error, but it wasn't really helpful. It wasn't too hard to find out what happened, since this particular engine has some variables to avoid problems with code set conversions and it was started without those variables in the environment. But It would have been quicker to understand if we had a proper error code. So, after solving the main issue, I dig in to the subject and found a very interesting APAR:

IC64220: THREADED OLEDB DOES NOT RETURN THE CORRECT ERROR MESSAGE

Basically, the driver was doing a bad use of the MS API to expose errors and in some situations the error structures were not properly initialized. This caused the "No error message available" information.
The fix is in CSDK 3.50.xC5 and if nothing else, this would be a good reason to upgrade.
It was not the first time I had "weird errors" in Windows environment, and in fact there were other similar bugs reported. So I leave here the suggestion to upgrade. Obviously, like with any other upgrade, test, test, test....

Portuguese version:

Há alguns artigos atrás eu dei um "sermão" sobre como fazer um bom despiste de problemas. E escrevi que tudo deve começar com um erro ou com um mau comportamento. Quando temos um erro devemos começar por aí. Se não tivermos é mais dificíl.... Mas e se tivermos um erro que diz:

"No error message available"

Nada bom... Encontrei uma situação num cliente onde isto apareceu. É uma aplicação Web escrita em ASP utilizando os drivers Windows (OleDB) a correr em IIS. Após uma paragem de um motor, começaram a ter o seguinte erro:

No error message available, result code: E_UNEXPECTED(0x8000FFFF)
ErrorCode -2147418113

Portanto, tinhamos um erro, mas não era grande ajuda. Não foi muito difícil descobrir o que se tinha passado, dado que este motor em particular tem algumas variáveis posicionadas para evitar problemas na conversão de caracteres entre diferentes mapas ou codesets, e estas variáveis não estavam posicionadas quando se arrancou com o motor. Mas teria sido mais rápido de entender se tivéssemos tido um código e mensagem de erro válidos. Assim, após resolver o problema principal, investiguei um pouco mais e encontrei o seguinte APAR:


IC64220: THREADED OLEDB DOES NOT RETURN THE CORRECT ERROR MESSAGE

Basicamente, o driver estava a fazer uma utilização errada da API da MS para expor erros, e em determinadas situações as estruturas de erro não eram devidamente inicializadas. Isto causava a mensagem "No error message available"

A correcção está no CSDK 3.50.xC5, e mesmo só por isto já seria uma boa razão para fazer a actualização.
Não foi a primeira vez que me deparei com erros "estranhos" no ambiente Windows, e na verdade havia outros bugs semelhantes reportados. Assim, deixo a sugestão para se fazer a actualização. Claro que em qualquer situação de actulização de versões, a ordem é testar, testar, testar....

Thursday, July 22, 2010

Informix Editions revisited / Versões Informix revisitadas

This article will be in English and Portuguese.
Este artigo será em Inglês e Português

English version:

After the announcements in May, new changes were made to Informix packaging. Basically the free versions for Windows and Mac OSX (Ultimate-C) were withdrawn. To replace them the Innovator-C version (also free, but with lower usage limits) will be available for all platforms (including the Windows and Mac OSX).

Also a new edition will be available, called Choice Edition, just for Windows and Mac OSX. This one will have license costs, but is cheaper than Growth Edition. The limits are higher than Innovator-C and lower than Growth Edition.

I believe these changes have created some confusion, but there are some important points to note:

  1. Clients will still be able to use a version without license costs for all platforms supported by Informix (Innovator-C). The usage limitations are fairly acceptable for a lot of usages
  2. Windows and Mac OSX are target platforms with a more aggressive price, considering Choice Edition (again, with fairly respectable functionality and usage limits)
  3. Existing customers are not necessarily affected by the new editions. They already payed for the licenses, and are (probably) paying maintenance/support. Obviously they can consider the new editions for new deployments
  4. Existing Enterprise Edition customers get more value, because Ultimate Edition includes more features than the Enterprise
The last changes were announced a few days ago and are explained in IIUG website, more specifically here:
http://www.iiug.org/news/announcements/new_prices.php

I delayed the publishing of this article because I was expecting the website comparing the different versions to be updated:

http://www.ibm.com/developerworks/data/library/techarticle/dm-0801doe/

This is the best, and the official place to check each version available functionality.

Other links:



Versão Portuguesa:

Depois dos anúncios em Maio, novas alterações foram feitas nas versões de Informix disponíveis. Basicamente as versões grátis para Windows e Mac OSX (Ultimate-C) foram descontinuadas. Para as substituir a versão Innovator-C (igualmente grátis, mas com limites de utilização mais baixos) estará disponível para todas as plataformas (incluindo Windows e Mac OSX)

Uma nova versão estará disponível, designada por Choice Edition, apenas para Windows e Mac OSX. Esta versão terá custos de licenciamento, mas será mais barata que a Growth Edition. Os limites situam-se entre a Innovator-C e a Growth Edition.

Acredito que estas alterações provoquem alguma confusão, mas há que salientar alguns pontos:

  1. Os clientes poderão utilizar uma versão sem custos em todas as plataformas suportadas pelo Informix (Innovator-C). As funcionalidades incluídas e os limites impostos não deverão ser obstáculo a um leque grande de ambientes.
  2. Windows e Mac OSX são plataformas alvo, com preços mais agressivos, considerando a versão Choice (também com funcionalidades e limites de utilização bastante respeitáveis.
  3. Os clientes existentes não são necessariamente afectados pelas novas versões. Na realidade o custo das licenças já foi pago, e o que estarão (provavelmente) a pagar são os custos de manutenção/suporte. Naturalmente poderão considerar as novas versões para novos projectos.
  4. Clientes actuais da Enterprise Edition obtém mais valor, porque a versão Ultimate incluí mais funcionalidade que a Enterprise
As últimas alterações foram anunciadas alguns dias atrás e estão explicadas no website do IIUG, mais especificamente aqui:

http://www.iiug.org/news/announcements/new_prices.php

Atrasei um pouco a publicação deste artigo porque estava à espera que o website que tem a comparação entre as versões fosse actualizado:

http://www.ibm.com/developerworks/data/library/techarticle/dm-0801doe/

Este é o melhor sitio (e o oficial) para verificar as funcionalidades e limites de cada versão.

Outros links: