Wednesday, August 03, 2016

Informix 12.10.xC7W1

A new PID (Post Interim Drop) for Informix (original version here: http://informix-technology.blogspot.com/2016/08/informix-1210xc7w1.html)


English version
Just a couple of weeks after the regular fixpack 12.10.xC7 IBM launches 12.10.xC7W1. The "W"s are cumulative releases (W2 contains everything W1 contains). They typically come out when there's a strong reason for it, like:

  1. Serious security or functional issue discovered in previous releases and it's yet to early to release the next fixpack
  2. When there are a considerable number of customers asking for specific patches on top of previous fixpack
  3. As part of a more frequent release plan (put the features out as soon as we have them)
 Non-officially, it was suggested this release was triggered by some Cognos (IBM BI software) requests as Informix is the embedded database for it.  But it was also suggested that we could expect more frequent PIDs in the future.

In any case some customers were concerned that a release of a PID so close to the fixpack release date could imply the fixpack (12.10.xC7) had serious issues. That doesn't seem to be the case, and no alert/flash was released.
For the customers that were in the process of planning upgrades to 12.10.xC7 they could consider using 12.10.xC7W1 instead. If you already moved, there seems to be no reason to redo the upgrade process.
12.10.xC7W1 naturally contains some more fixes (that were not ready for 12.10.xC7) and a couple of features that will be made public in 12.10.xC8.


Versão Portuguesa
Apenas um par de semanas depois do fixpack regular 12.10.xC7 a IBM lança a 12.10.xC7W1. Os "W"s são versões cumulativas (W2 contém tudo o que a W1 contém). São lançadas tipicamente quando existe uma razão forte para isso, tais como:
  1. Problemas funcionais ou de segurança fortes descobertos na versão anterior, e quando ainda é muito cedo para lançar o próximo fixpack
  2. Quando há um número considerável de clientes a pedir patches específicos sobre o fixpack anterior
  3. Como veículo de um plano de releases com maior frequência de versões (disponibilizar as funcionalidades assim que as temos)
Não oficialmente foi sugerido que este PID derivou de necessidades do Cognos (software de BI da IBM), visto que o Informix serve de repositório ao Cognos. Mas foi também sugerido que no futuro poderemos ver estes PIDs com mais frequência

Em todo o caso, alguns clientes manifestaram preocupação com a disponibilização de um PID tão em cima da disponibilização de um fixplck regular, pois isso poderia indicar problemas sérios no fixpack 12.10.xC7. Não aparenta ser esse o caso e não foi efetuado nenhum alert/flash relativo ao Informix.

Para clientes que estavam no processo de migração para a 12.10.xC7, poderiam considerar utilizar a 12.10.xC7W1. Se já efetuou o upgrade para a 12.10.xC7 não parece haver motivo imperativo que leve a mudar para a 12.10.xC7. A 12.10.xC7W1 naturalmente contém mais correções (que não estavam prontos na data da 12.10.xC7 e um ar de funcionalidades que será tornada pública quando sair a 12.10.xC8.

Thursday, July 28, 2016

Informix 12.10.xC7

A description of the new features introduced in Informix fixpack 12.10.xC7 (original version here: http://informix-technology.blogspot.com/2016/06/informix-1210xc7.html)


English version
And another fixpack has come out. Informix 12.10.xC7 has been available to customers for around  two weeks. The documentation is available in the Knowledge Center.

The new fixpack will not be known as the greatest ever. The list of features is not long, and more important is highly dedicated to the new features we've been seeing in the latest releases. Things like JSON, Spatial temporal and Timeseries have been the main focus of the enhancements. I'd call this essentially a stability and IoT release. However, not all new features were documented (more on this later). Let's dig into the list:

  • Application development
    • COALESCE function
      This is the only "regular SQL" enhancement. The COALESCE() function accepts an undetermined number of arguments and returns the first non NULL value. It's a sort of glorified NVL(). This is important for compatibility with other vendors, specially considering this would not be possible to implement in a custom function (considering the unknown number and type of the arguments)
  • JSON compatibility
    • Update BSON arrays in an SQL statement
      New MongoDB operators were added to the list of possibilities in the BSON_UPDATE() function: $addToSet, $pop, $pullAll, and $push, plus the array update operator modifiers $each, $position, $slice, and $sort
    • JSON compatibility enhancements
      Several improvements in the JSON handling and MongoDB compatibility:
      • The behavior of the wire listener was changed. Now it send the updates to the database server first. Before the updates were run on the listener
      • We can now use bind variables in SQL statements sent through the wire listener
      • Even if the SQL statements feature is disabled we can activate the execution of procedures and functions. This allows greater control and security without allowing generic SQL execution
      • The transaction command can be used to execute several statements as a single transaction.
      • Compatibility with MongoDB shell version 3.2
      • GridFS functionality (available in the MongoDB drivers) can be used with Informix. This functionality was introduced as a way to sotre files in MongoDB that exceed the 16MB limit of MongoDB objects (note that Informix limit is 2GB).
        This splits the file into smaller chunks and stores the chunks in one collection and the metadata of the file in another collection
      • You can now use the MongoDB aggregation framework pipeline to aggregate time series data or return the time series element in a time range.
    • Load JSON documents with the MQTT protocol
      The MQTT protocol is an ISO lightweight protocol defined to allow sensors and other endpoint devices to send data to repositories or message brokers. Now Informix wire listener can be configured as an MQTT protocol receiver so that data can be sent to the database without further programming
    • Quickly add or remove shard servers with consistent hashing
      A new sharding method, "chash" or consistent hashing allows a member to be added or removed to a sharded object (table or collection) without having to redistribute all the data (only part has to be distributed)
  • Spatiotemporal searching
    • Improved spatiotemporal searching
      There are many improvements in this area. They are very specific and the description requires knowledge of what spatioltemporal data is and how it works. One highlight is the fact that the distance measures now are done in a spherical model and not the old Cartesian one. This was previously done for the spatial datablade and is very important considering the old method would introduce significant errors in the calculations (specially for longer distances and some parts of the globe)
  • Time series
    • Trigger spatiotemporal indexing while loading time series data
      New option allows us to require the indexing of spatiotemporal data when TimeSeries loaded data is written to disk
    • Improved pattern match searching
      TimeSeries pattern matching on BSON documents for numeric data and TimeSeries sub-type
    • Limit future data for rolling window containers
      We can define how many partitions "in the future" can be added. This may avoid that some application or user mistakes delete valid (old) data partitions
    • Enhancements for hertz data
      Removal of some limitations. Hertz (sub-second) data can be inserted after more recent data (out of chronological order), although within a second the order must be respected. And this type of data can now use rolling window containers
    • Longer fragmentation schemes for time series virtual tables
      I have troubles understanding this feature... Apparently the statement for a virtual table creation on top of a timeseries structure could result in an SQL statement that exceeds the maximum size of an SQL statement. So two flags were created to shorten the statement, depending on the scheme used in the base table. What puzzles me is that the SQL statement size was hugely increased in some recent versions
  • Spatial data
    • Convert spatial data to GeoJSON format
      A new function, SE_AsBSON() can be used to convert spatial data into the Geo/JSON format for applications that handle preferably JSON formatted data  
Now... about the non-documented features... Actually this fixpack introduces two important changes that were not (initially at least) documented:
  • The Informix Warehouse Accelerator (the in-memory database add-on that works together with Informix) can now be installed on Linux running on Power8 processors running in Little Endian mode.After several years since it's introduction when we told customers that this component had been designed for Intel processors IBM changes the game. This doesn't mean that what was told to customers was not true... The product really required a special type of instructions called SMD (Single introduction Multiple Data) that were present on Intel processors. Actually these were also present in Power processors, but the programming needed to be adapted to really take advantage of them since the use of these instructions really depends on the data layout in memory. IBM decided to do it now eventually taking advantage that with the Little Endian mode the data layouts will be equal on both platforms. And on the IIUG conference Sandor Szabo made a presentation comparing the product performance in both technologies with a clear advantage for Power. Naturally with anything related to CPUs, we already know it's a leap frog game. Anyway, now customers have a choice for the platform where they'll run the IWA component and this is specially relevant for IBM since it has sold it's x86 line of servers to Lenovo a few years ago.
  • The second feature is "small" but may be very relevant. We introduced the ability to create foreign key constraints with the NOVALIDATE option a few fixpacks ago. Now this was extended to the check constraints. Besides the typical scenario of export/import the other very useful use case for this is when we need to attach a table as a new partition of an existing and already partitioned table. By default Informix will validate that the data in the table validates the expression used for partitioning. This can consume a significant amount of time during the attach, which is clearly undesirable. The workaround was to create a check constraint matching the expression. Informix is smart enough to understand the data is ok, because we have the check constraint. This would consume time, but it could be done prior to the attach during data preparation. Now the constraint can be created with the NOVALIDATE option and that means much faster operations.


Versão Portuguesa
E saiu outro fixpack do Informix, 12.10.xC7. Está disponível para os clientes há cerca de duas semanas. A documentação está acessível no  Knowledge Center.

Este novo fixpack não ficará conhecido como o maior de sempre. A lista de novidades não é longa e mais importante que isso é altamente dedicada às novas áreas que temos visto nas últimas versões. Áreas como JSON, espaço temporal, timeseries têm sido o principal foco das melhorias. Chamar-lhe-ia essencialmente uma versão de estabilidade e dedicada à IoT. Em todo o caso nem todas as novidades foram documentadas (mais sobre isto adiante). Analisemos então a lista:
  • Desenvolvimento de aplicações
    • Função COALESCE
      Esta é a única melhoria do "SQL normal". A função COALESCE() aceita um número indeterminado de argumentos e retorna o primeiro valor não NULO. Como se fosse uma versão glorificada do NVL(). É importante para compatibilidade com outros fornecedores, especialmente porque devido ao número e tipo indeterminado de argumentos, isto não era algo fácil de implementar como uma função desenvolvida pelos utilizadores
  • Compatibilidade JSON
    • Update arrays BSON em instruções SQL
      Novos operadores MongoDB foram adicionados à liste de possibilidades da função BSON_UPDATE(): $addToSet, $pop, $pullAll, e $push, mais os modificadores de operadores  em update array $each, $position, $slice, e $sort
    • Melhorias de compatibilidade JSON
      Várias melhorias na manipulação de JSON e melhor compatibilidade com MongoDB
      • O comportamento do wire listenert foi modificado. Agora envia os updates para a base de dados como primeira opção. Antes os updates eram feitos pelo listener
      • Possibilidade de usar bind variables em instruções SQL enviadas através do wire listener
      • Mesmo que a funcionalidade de envio de SQL esteja desativada é possível ativar a execução de procedimentos e funções. Isto permite maior controlo e segurança por não deixar enviar SQL genérico
      • O comando de transação pode ser usado para executar várias instruções dentro da mesma transação
      • Compatibilidade com a versão 3.2 do MongoDB shell
      • A funcionalidade GridFS (disponível nos drivers MongoDB) pode agora ser usada com Informix. Esta funcionalidade foi introduzida como uma forma de guardar ficheiros no MongoDB que ultrapassassem os 16MB de limite dos objectos em  MongoDB. (note-se que em Informix o limite é de 2GB)
        A funcionalidade parte o ficheiro em pedações mais pequenos e guarda-os numa collection e a metadata sobre os mesmos noutra collection.
      • Possibilidade de utilização da pipeline da framework de agregação do MongoDB para agregar dados TimeSeries ou retornar os elementos TimeSeries num intervalo de tempo
    • Carregar documentos JSON com o protocolo MQTT
      O protocolo MQTT é um protocolo "leve" definido pelo comité ISO para sensores e outros dispositivos terminais, com o objetivo de enviar dados para repositórios de dados ou gestores de mensagens.
      Agora o wire listener do Informix pode ser configurado como um receptor do protocolo MQTT, de forma a que os dados possam ser-lhe enviados sem qualquer programação
    • Adição e remoção rápida de servidores shard com consistent hashing
      Um novo método de sharding, "chash" ou hashing  consistente permite que um membro seja adicionado ou removido a um objeto (tabela ou collection) sem que se tenha de redistribuir todos os dados (apenas uma parte será redistribuída)
  • Pesquisa Spatiotemporal
    • Melhorias na pesquisa spatiotemporal
      Existem muitas novidades nesta área. São muito específicas e a explicação requer um bom entendimento do que são dados spatiotemporal e como funcionam. Um ponto em destaque é o facto de as medidas de distâncias passarem a ser feitas no modelo "esférico" e não no antigo cartesiano. Isto foi introduzido anteriormente no spatial datablade e é muito importante considerando que o método antigo introduzia erros consideráveis nestes cálculos (em particular para distâncias mais longas e certas regiões do globo terrestre)
  • Timeseries
    • Despoletar indexação spatiotemporal durante o carregamento de dados timeseries
      Uma nova opção permite-nos requerer a indexação spatiotemporal enquanto os dados TimeSeries são carregados e escritos em disco
    • Melhoria na pesquisa  pattern match
      TimeSeries "pattern matching" em documentos BSON para dados numéricos e sub-tipo TimeSeries
    • Limite para dados futuros em rolling window containers
      Podemos definir quantas "partições" "no futuro" podem ser adicionadas. Isto pode evitar que alguma aplicação ou utilizador possa, por erro, apagar partições antigas que sejam ainda válidas
    • Melhoria para dados "hertzianos"
      Remoção de algumas limitações. Dados "hertzianos" (sub-segundo) podem ser inseridos após dados mais recentes (fora da ordem cronológica), embora dentro de um mesmo segundo a ordem tenha de ser respeitada. Este tipo de dados pode agora ser também usar rolling window containers
    • Esquemas de fragmentação mais longos para tabelas virtuais sobre timeseries
      Confesso que tenho alguns problemas em entender esta funcionalidade... Aparentemente a instrução para criação de uma tabela virtual sobre uma estrutura timeseries poderia resultar numa instrução que excedesse o limite de tamanho de uma instrução SQL. Para o evitar foram criadas duas flags que permitem encurtar a instrução, dependendo do esquema de fragmentação existente na tabela base. O que me intriga é que o tamanho de uma instrução SQL foi enormemente aumentado em versões recentes, pelo que me parece impensável à partida que pudesse ser atingido
  • Dados Spatial
    • Conversão de dados spatial para formato GeoJSON
      Uma nova função, SE_AsBSON() pode ser usada para converter dados spatial para o formato GeoJSON em aplicações que prefiram lidar com este formato

Agora... sobre as funcionalidades não documentadas.... Na verdade, este fixpack introduz duas mudanças importantes que não foram (inicialmente pelo menos) documentadas:
  • O Informix Warehouse Accelerator (o componente de base de dados em memória que trabalha em conjunto com o Informix) pode agora ser instalado em Linux a correr em processadores Power8 configurados no modo de Little Endian. Após vários anos desde a introdução do produto em que foi dito aos clientes que o mesmo tinha sido desenhado para processadores Intel a IBM decidiu mudar o "jogo". Isto não quer dizer que o que foi dito aos clientes não fosse verdade... O produto realmente necessita um tipo especial de instruções no CPU, chamadas SMD (Single instruction Multiple Data) que existe nos processadores Intel. Mas na verdade os processadores Power também têm o mesmo tipo de instruções, mas a programação tinha de ser alterada / reoptimizada (este tipo de instruções depende da disposição de dados em memória). E a IBM decidiu fazê-lo agora, porventura tirando partido de as diferenças em modo Little Endian serem menores. Na conferência do IIUG o Sandor Szabo efetuou uma apresentação que compreendia uma comparação do produto em ambas as plataformas com vantagem clara para a arquitetura Power. Naturalmente com tudo o que está relacionado com CPUs, todos sabemos que se trata de "saltos de rã", ou seja, uma futura geração de processadores Intel pode reverter estas observações ou minimizar as diferenças.
    De qualquer forma os clientes agora têm duas opções para executar o IWA, sendo isto relevante para a IBM visto que vendeu a sua linha de servidores Intel à Lenovo há uns anos atrás
  • A segunda funcionalidade parece pequena mas é relevante. Introduzimos a possibilidade de criar constraints do tipo chave estrangeira com a opção de NOVALIDATE há uns fixpacks atrás. Agora a opção foi estendida às check constraints. Para além do cenário óbvio de exportação/importação de dados a outra situação em que isto pode ser muito útil é quando queremos adicionar uma tabela como uma nova partição a uma tabela já existente e já particionada. Por omissão o Informix vai validar que os dados existentes na tabela que será o novo fragmento verificam a expressão de particionamento utilizada. Isto pode consumir muito tempo e é feito durante o attach o que é claramente indesejável. A forma de contornar isto seria criar uma check constraint com a mesma condição de particionamento usada na nova partição. O Informix é suficientemente esperto para perceber que se existe uma constraint não tem de voltar a fazer a validação. Ainda assim demorava-se tempo ainda que durante a fase de preparação dos dados. Agora com a possibilidade de criar as check constraints com a cláusula NOVALIDATE poupa-se esse tempo, tornando este tipo de operação muito mais rápido

Thursday, May 05, 2016

11.50 EOS / Fim de suporte 11.50

IBM as published EOS dates for Informix 11.50 (original version http://informix-technology.blogspot.com/2016/05/1150-eos-fim-de-suporte-1150.html)


English version
IBM has recently announced the End Of Support (EOS) dates for version 11.50 of Informix. The details can be checked at http://www.ibm.com/software/data/support/lifecycle/ but in short the 11.50 will be out of support after April 30 2018.
The first release of 11.50 was on May 13, 2008. This means IBM supported this particular version for 10 years.That's not usual in the industry.

After 11.50 IBM released 11.70 and 12.10 which is currently on it's sixth fixpack and is considered mature.
Customers still have around 2 years to plan for migrations which should be more than enough.
As of today I would recommend any customer to move to 12.10, for the following reasons:

  • 12.10 is on FC6 and is stable
  • 12.10 has much more features than 11.70 and will probably receive further more in upcoming fixpacks
  • 11.70 will have a shorter support time compared to 12.10
  • The tasks, tests and risks of migrating to 12.10 are exactly the same as for 11.70
So, in short, why plan to move to an older version, if you have a newer one which is stable, has more features and that will require the same steps to migrate to?

The question will become more difficult to answer is in the meantime IBM releases another version.



Versão Portuguesa
A IBM anunciou recentemente a data para fim de suporte das versões 11.50 do Informix. Os detalhes podem ser consultados em: http://www.ibm.com/software/data/support/lifecycle/ mas de forma resumida a versão 11.50 ficará sem suporte em30 de Abril de 2018
A primeira versão 11.50 foi anunciada em13 de Maio de 2008. Isto significa que a IBM suportará esta versão por 10 anos. Isto excede claramente o padrão dos fornecedores de tecnologia.

Apóas a 11.50 a IBM lançou a 11.70 e a 12.10 que atualmente está no seu sexto fixpack e pode ser considerada "madura". Os clientes ainda têm cerca de 2 anos para planear as migrações o que deverá ser mais que suficiente.
À data de hoje, eu recomendaria a qualquer cliente que migrasse para a 12.10 pelas seguintes razões:
  • A 12.10 está na FC6 e está estável
  • A 12.10 tem muito mais funcionalidades que a 11.70 e deverá receber mais melhorias nos próximos fixpacks
  • A 11.70 terá uma vida mais curta quando comparando com a 12.10
  • As tarefas, testes e risco de migração para a 12.10 serão semelhantes à migração para a 11.70
Portanto, em resumo, porquê planear uma migração para uma versão mais antiga, se temos uma mais recente que está estável, tem mais funcionalidades e que requer o mesmo nível de esforço?

A questão poderá ser mais difícil de responder se neste intervalo de tempo a IBM lançar uma nova versão.


Thursday, April 07, 2016

Error -76719 / Erro -76719

If you see this error, you're most likely using a J2EE application server, and you have a firewall between it and your database (original version http://informix-technology.blogspot.com/2015/02/error-76719-erro-76719.html)




English version
I've found this error many times. And recently it happened again while working on a customer. Invariably it happens on application servers with a firewall between them and the database. The error description is:

-79716    System or internal error.

An operating or runtime system error or a driver internal error
occurred.

The accompanying message describes the problem.

Often the error also shows this message:

java.net.SocketException: Broken pipe

If you find this, most likely you have a firewall between the database and the application server and your firewall is forcing the closing of the sockets. Why would it do that? Typically the firewalls are configured to close connections they consider "idle" for a period of time. And usually in an application server, using connection pooling it may happen that a specific connection is not used for many minutes. Without traffic in the connection the firewall will decide the connecting is "forgotten" and will close it. To be honest this is the part I never was able to figure out... when a system decides to close a socket, a signal (13) is usually sent to the endpoints. Upon receiving the signal, the client and server learn the connection was broken and they can create another one, or raise an appropriate error. The problem I'm used to, is that the client (in this case the J2EE application server) never receive (or ignore?) that signal. So they don't "know" the socket is not there anymore. Instead they keep the socket reference associated with a connection that is part of their pools. Once a client application requests a connection from the pool, it may get one of these "phantom" connections. When it tries to send the SQL request, the exception is generated and the error is raised.
All this explains the problem. But what we really want is the solution. And that is a bit more complex to explain but trivial to implement. In fact there are two solutions:

  1.  Have you network administrators change the firewall rules either to increment the period before considering a connection as stale, or to ignore Informix connections. I never saw a situation where this happened. Somehow the network admins act like dictators and they refuse any change.
  2. Force some sort of traffic through the connection so that the firewall doesn't think the connection is stale
As mentioned, the first option is usually not considered possible. And the second is easy to implement. Thankfully the operating systems already have a mechanism to test the connections which is called "keepalive" or "keepalive probes". The idea is very simple. At specific intervals the system sends a "probe" (special packet) to the other side and wait until either a response is received or a timeout is reached. Keep in mind this is an OS mechanism. And as you would expect it requires a few things to work:
  1. That the OS "decides" to activate the mechanism (as we'll see we can direct Informix to ask for it)
  2. That we configure the "interval" at which a "probe" will be sent
  3. That we configure the maximum time to wait for an answer
  4. Eventually that we configure the number of probes to send before assuming the connection is not good if no answer is received
Typical defaults imply that keepalive is not used, and that the interval is 7200 seconds (2H). Not all operating systems have the timeout and number of probes as parameters.. But I mentioned that there is a way to instruct Informix to request for the keepalive mechanism on it's sockets. Currently we can do it on the server side and on the client (JDBC) side:
  • On the server side just adding a "k=1" to the $INFORMIXSQLHOSTS options field
  • On the client (JDBC) side just add the property IFX_SOC_KEEPALIVE and set it to true. Note that this is available only on version 4.10.JC6+
Keep in mind that these options only request the OS to activate the keepalive functionality. The intervals and timeouts must be configured at the operating system level where the Informix functionality is activated. Informix does not send any "fake" traffic by itself.

Another option on some application servers would be to "test" the connections (usually requires some dummy and simple query), or define a maximumage for the connections. But these configurations depend on your application server 

A final note: Sometimes we need to check if an opened socket is using the keepalive option. In most operating systems we can use the lsof command with the option "-Tf". This adds the socket options used to open the socket (or added later) to the output. But this option does not work on Linux. In this OS we can use the netstat command with the "-o" option:


castelo@primary:informix-> netstat -no | grep ":10000"
tcp        0      0 192.168.142.202:10000       192.168.142.202:33053       ESTABLISHED keepalive (5332.90/0/0)
tcp        0      0 192.168.142.202:33053       192.168.142.202:10000       ESTABLISHED keepalive (5332.88/0/0)
castelo@primary:informix->
 


The number shown between parenthesis is the counter till the sending of the next probe.





Versão Portuguesa
Encontrei este erro muitas vezes. E voltou a acontecer novamente enquanto estava num cliente. Invariavelmente isto acontece quando existe um firewall entre um servidor aplicacional (normalmente J2EE) e a base de dados. A descrição do erro é:

-79716    System or internal error.

An operating or runtime system error or a driver internal error
occurred.

The accompanying message describes the problem.

Muitas vezes aparece também a seguinte mensagem:

java.net.SocketException: Broken pipe

Se encontrar isto, a probabilidade é que exista um firewall entre o servidor aplicacional e a base de dados que esteja a fechar os sockets de comunicação. Porque o haveria de fazer? Porque tipicamente os firewalls estão configurados para fecharem as ligações que consideram inativas por um determinado período de tempo. E é normal que num servidor aplicacional que utilize connection pooling uma determinada conexão pode não ser usada durante largos minuto. Sem tráfego na ligação o firewall irá considerá-la como "esquecida" e fechá-la-á. Para ser honesto esta é a parte que nunca percebi.... Quando um sistema quebra uma ligação (por interrupção física da comunicação por exemplo) a aplicação associada ao socket normalmente recebe um sinal (13). Ao receber este sinal a aplicação sabe que a conexão foi fechada e pode tomar as ações apropriadas, como recriá-la ou gerar um erro.
O problema a que me habituei é que o cliente (neste caso o servidor aplicacional J2EE) nunca recebe (ou porventura ignora?) o sinal. Por isso não "sabe" que o socket já não existe. E portanto mantém uma referência a um socket que já não existe na sua pool de conexões. Quando uma aplicação pede uma conexão dessa pool pode receber a referência "fantasma". E ao tentar usá-la para enviar uma instrução SQL para a base de dados é gerada a exceção com o erro referido.
Tudo isto explica o problema. Mas o que queremos realmente é resolvê-lo. E isso é um pouco mais complicado de explicar, mas simples de implementar. De facto há duas soluções:

  1. Fazer com que os administradores de rede mudem as regras do firewall para aumentar o período de inatividade aceitável ou para ignorar completamente as conexões ao informix. Nunca presenciei uma situação onde tal acontecesse. Por algum motivo que me ultrapassa os administradores de rede atuam como ditadores e recusam qualquer mudança
  2. Forçar o envio de algum tipo de tráfego através de cada conexão para que o firewall não a considere "inativa"
Como referido, a primeira opção normalmente não é considerada. E a segunda é fácil de implementar. Felizmente os sistemas operativos já dispõem de um mecanismo que testa as conexões, o qual é chamado de "keepalive" ou "keepalive probes". A ideia é muito simples. De tempos a tempos o sistema envia uma "sonda" (pacote especial) para a outra ponta da conexão e espera por uma resposta ou que seja atingindo um timeout. Não nos esqueçamos que isto é um mecanismo do sistema operativo. E para tal há que configurar algumas coisas para que funcione adequadamente:
  1. Que o SO "decida" ativar o mecanismo para determinadas conexões (como veremos podemos configurar o Informix para requisitar isto ao SO)
  2. Que se configure o "intervalo" de teste das ligações (quando serão enviadas as "sondas")
  3. Que se configure o tempo máximo para receção da resposta
  4. Eventualmente que se configurem o número de "sondas" a serem enviadas e que fiquem sem resposta antes de o SO considerar a ligação como "morta"
Por omissão, muitas vezes o mecanismo de keepalive não é utilizado. E os intervalos frequentement estão definidos para 7220s (2H). Nem todos os sistemas operativos usam os parâmetros para timeouts e retries.
Atrás referi que é possível forçar o Informix a activar este mecanismo no SO. Atualmente podemos fazer isso no lado do servidor e no lado do cliente (JDBC)::
  • No lado do servidor basta acrescentar a opção "k=1" no campo das opções no $INFORMIXSQLHOSTS
  • No cliente (JDBC) basta adicionar a propriedade IFX_SOC_KEEPALIVE com o valor true. Note-se que isto só está disponível nas versões 4.10.JC6+
Saliento que estas opções só pedem ao SO que ative a funcionalidade de keepalive. Os intervalos e timeouts serão configurados com ferramentas do sistema operativo. O Informix nunca envia "falso" tráfego por ele próprio.

Outra opção em alguns servidores aplicacionais seria "testar" as conexões (normalmente com uma query simples e rápida), ou definir uma idade máxima para as conexões. Mas estas configurações dependem de servidor para servidor.

Uma nota final: Por vezes é necessário perceber ou verificar se um socket aberto tem mesmo a opção de keepalive ativa. Na maioria dos sistemas operativos podemos usar o comando lsof com a opção "-Tf". Isto acrescenta as flags usadas na abertura do socket. Mas esta opção não funciona em Linux. Neste SO pode usar-se o "netstat" com a opção "-o":

castelo@primary:informix-> netstat -no | grep ":10000"
tcp        0      0 192.168.142.202:10000       192.168.142.202:33053       ESTABLISHED keepalive (5332.90/0/0)
tcp        0      0 192.168.142.202:33053       192.168.142.202:10000       ESTABLISHED keepalive (5332.88/0/0)
castelo@primary:informix->
 


O número entre parenteses é o contador até ao envio da próxima "sonda"