• Tutorial
  • Crond para reset de senhas em contêiner docker

Com a nova versão 2.2.1 percebi que mudou o caminho para execução do crond por ser um contêiner com o Alpine Linux, diferente da 2.1.9., mas que não muda muita coisa apenas uma pequena adaptação.

Entre no console do contêiner do NovoSga
No meu caso criei um arquivo com o script no diretório /etc/periodic/daily/ para reset diário as 2 da manhã (caso queira ver as configurações padrões digite crontab -e no console)
Entre no diretório:
cd /etc/periodic/daily/

Crie o arquivo:
vi novosga-reset

Coloque esse conteúdo:

#!/bin/sh
echo "$(date '+%Y-%m-%d %H:%M:%S') - Script executado!" >> /var/log/novosga-reset.log
/usr/bin/php /var/www/html/bin/console novosga:reset >> /var/log/novosga-reset.log 2>&1

salve
:wq

Dar permissão de execução

chmod +x novosga-reset

Caso não queira esperar virar o dia teste manualmente

run-parts /etc/periodic/daily

Verifique se houve registro no log em:
cat /var/log/novosga-reset.log

Aqui rodou perfeitamente.

andersonmnz alterou o título para Crond para reset de senhas em contêiner docker .
19 dias depois

Tentei executar esse tutorial no novosga 2.2.6, tem alguma informação se está funcionando? Aqui quando eu executo

run-parts /etc/periodic/daily

ele da certo, porem automatico, sem sucesso

Eu instalei o crond via apk add, mas quando o conteiner é reiniciado ele volta ao estado do dockerfile que provavelmente não tem o cron para execução e aí não executa o script.
Assim creio que seja necessário..., ou recriar o dockerfile com o serviço ou usar o docker exec do crond a partir do host para executar o script, mas vou testar ainda.

7 dias depois
  • Editado

Segui oque você pediu e aqui tbm não de certo, se rodo manualmente ele me retorna esse log:

2025-05-15 14:26:13 - Script executado!
{"message":"User Deprecated: Using ArrayAccess on Doctrine\\ORM\\Mapping\\JoinColumnMapping is deprecated and will not be possible in Doctrine ORM 4.0. Use the corresponding property instead. (ArrayAccessImplementation.php:31 called by DoctrineHelper.php:42, https://github.com/doctrine/orm/pull/11211, package doctrine/orm)","context":{"exception":{"class":"ErrorException","message":"User Deprecated: Using ArrayAccess on Doctrine\\ORM\\Mapping\\JoinColumnMapping is deprecated and will not be possible in Doctrine ORM 4.0. Use the corresponding property instead. (ArrayAccessImplementation.php:31 called by DoctrineHelper.php:42, https://github.com/doctrine/orm/pull/11211, package doctrine/orm)","code":0,"file":"/var/www/html/vendor/doctrine/deprecations/lib/Doctrine/Deprecations/Deprecation.php:210"}},"level":200,"level_name":"INFO","channel":"deprecation","datetime":"2025-05-15T09:26:14.297476-05:00","extra":{}}
{"message":"User Deprecated: Doctrine\\DBAL\\Connection::exec is deprecated, please use executeStatement() instead. (Connection.php:1992 called by MySQLStorage.php:53, https://github.com/doctrine/dbal/pull/4163, package doctrine/dbal)","context":{"exception":{"class":"ErrorException","message":"User Deprecated: Doctrine\\DBAL\\Connection::exec is deprecated, please use executeStatement() instead. (Connection.php:1992 called by MySQLStorage.php:53, https://github.com/doctrine/dbal/pull/4163, package doctrine/dbal)","code":0,"file":"/var/www/html/vendor/doctrine/deprecations/lib/Doctrine/Deprecations/Deprecation.php:210"}},"level":200,"level_name":"INFO","channel":"deprecation","datetime":"2025-05-15T09:26:14.297665-05:00","extra":{}}
{"message":"User Deprecated: Using ArrayAccess on Doctrine\\ORM\\Mapping\\JoinColumnMapping is deprecated and will not be possible in Doctrine ORM 4.0. Use the corresponding property instead. (ArrayAccessImplementation.php:31 called by DoctrineHelper.php:42, https://github.com/doctrine/orm/pull/11211, package doctrine/orm)","context":{"exception":{"class":"ErrorException","message":"User Deprecated: Using ArrayAccess on Doctrine\\ORM\\Mapping\\JoinColumnMapping is deprecated and will not be possible in Doctrine ORM 4.0. Use the corresponding property instead. (ArrayAccessImplementation.php:31 called by DoctrineHelper.php:42, https://github.com/doctrine/orm/pull/11211, package doctrine/orm)","code":0,"file":"/var/www/html/vendor/doctrine/deprecations/lib/Doctrine/Deprecations/Deprecation.php:210"}},"level":200,"level_name":"INFO","channel":"deprecation","datetime":"2025-05-15T09:26:14.297476-05:00","extra":{}}
{"message":"User Deprecated: Doctrine\\DBAL\\Connection::exec is deprecated, please use executeStatement() instead. (Connection.php:1992 called by MySQLStorage.php:53, https://github.com/doctrine/dbal/pull/4163, package doctrine/dbal)","context":{"exception":{"class":"ErrorException","message":"User Deprecated: Doctrine\\DBAL\\Connection::exec is deprecated, please use executeStatement() instead. (Connection.php:1992 called by MySQLStorage.php:53, https://github.com/doctrine/dbal/pull/4163, package doctrine/dbal)","code":0,"file":"/var/www/html/vendor/doctrine/deprecations/lib/Doctrine/Deprecations/Deprecation.php:210"}},"level":200,"level_name":"INFO","channel":"deprecation","datetime":"2025-05-15T09:26:14.297665-05:00","extra":{}}
{"message":"Error thrown while running command \"novosga:reset\". Message: \"An exception occurred while executing a query: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '21' for key 'PRIMARY'\"","context":{"exception":{"class":"Doctrine\\DBAL\\Exception\\UniqueConstraintViolationException","message":"An exception occurred while executing a query: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '21' for key 'PRIMARY'","code":1062,"file":"/var/www/html/vendor/doctrine/dbal/src/Driver/API/MySQL/ExceptionConverter.php:62","previous":{"class":"Doctrine\\DBAL\\Driver\\PDO\\Exception","message":"SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '21' for key 'PRIMARY'","code":1062,"file":"/var/www/html/vendor/doctrine/dbal/src/Driver/PDO/Exception.php:28","previous":{"class":"PDOException","message":"SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '21' for key 'PRIMARY'","code":23000,"file":"/var/www/html/vendor/doctrine/dbal/src/Driver/PDO/Statement.php:130"}}},"command":"novosga:reset","message":"An exception occurred while executing a query: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '21' for key 'PRIMARY'"},"level":500,"level_name":"CRITICAL","channel":"console","datetime":"2025-05-15T09:26:14.302277-05:00","extra":{}}
09:26:14 CRITICAL  [console] Error thrown while running command "novosga:reset". Message: "An exception occurred while executing a query: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '21' for key 'PRIMARY'" ["exception" => Doctrine\DBAL\Exception\UniqueConstraintViolationException { …},"command" => "novosga:reset","message" => "An exception occurred while executing a query: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '21' for key 'PRIMARY'"]
{"message":"Command \"novosga:reset\" exited with code \"1062\"","context":{"command":"novosga:reset","code":1062},"level":100,"level_name":"DEBUG","channel":"console","datetime":"2025-05-15T09:26:14.323165-05:00","extra":{}}

In ExceptionConverter.php line 62:
                                                                                                                                               
  An exception occurred while executing a query: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '21' for key 'PRIMARY'  
                                                                                                                                               

In Exception.php line 28:
                                                                                                
  SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '21' for key 'PRIMARY'  
                                                                                                

In Statement.php line 130:
                                                                                                
  SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '21' for key 'PRIMARY'  
                                                                                                

novosga:reset [-s|--seguro] [--] [<unidade>]

Poderia me dizer oque esta dando erro?

    Jander seu banco MySQL perdeu a sequência da tabela de senhas e voltou o ID para 1, aí quando tenta mover para o histórico dá erro de chave duplicada. Precisa acertar esses IDs para depois mover os dados.

      lhfc93 isso vai acontecer sempre que o MySQL5 reiniciar e a tabela de atendimento estiver vazia. O auto_increment até a versão 5.7 fica em memória, e quando o banco reinicia ele inicia essa sequência com o maior valor da tabela. Nesse caso, após mover os dados para o histórico, a tabela fica vazia fazendo com que a contagem volte para 1.

        17 dias depois

        rogeriolino Só pra eu entender melhor essa situação, o que faz com que a tabela de atendimento fique vazia? Essa tabela seria um lugar intermediário, onde os atendimentos permanecem até serem "transferidos" para outro lugar? E como evitar que essa situação ocorra? Como evitar que seja feito reset com essa tabela estando vazia?
        Só quero entender melhor essa situação, até pra tentar evitar o problema.

          fbravo o reset de senhas limpa a tabela de atendimento (atendimentos), movendo os dados para o histórico (historico_atendimentos).

          No MySQL5 não tem como evitar o problema, tem como acertar, aí é marretar o banco. A solução é subir para o MySQL8 (compatível com o NovoSGA v2.2).

          MySQL 5.7
          https://dev.mysql.com/doc/refman/5.7/en/innodb-auto-increment-handling.html

          InnoDB AUTO_INCREMENT Counter Initialization
          If you specify an AUTO_INCREMENT column for an InnoDB table, the table handle in the InnoDB data dictionary contains a special counter called the auto-increment counter that is used in assigning new values for the column. This counter is stored only in main memory, not on disk.

          MySQL 8
          https://dev.mysql.com/doc/refman/8.0/en/innodb-auto-increment-handling.html

          InnoDB AUTO_INCREMENT Counter Initialization
          If you specify an AUTO_INCREMENT column for an InnoDB table, the in-memory table object contains a special counter called the auto-increment counter that is used when assigning new values for the column.
          In MySQL 5.7 and earlier, the auto-increment counter is stored in main memory, not on disk. To initialize an auto-increment counter after a server restart, InnoDB would execute the equivalent of the following statement on the first insert into a table containing an AUTO_INCREMENT column.
          In MySQL 8.0, this behavior is changed. The current maximum auto-increment counter value is written to the redo log each time it changes and saved to the data dictionary on each checkpoint. These changes make the current maximum auto-increment counter value persistent across server restarts.