From 9d710d8e2eb5de9844481ab4d4d3776acec21b95 Mon Sep 17 00:00:00 2001 From: Dan Garner Date: Fri, 7 Feb 2025 17:05:01 +0000 Subject: [PATCH] MySQL: retry on 2006 audit log failure xibosignage/xibo#3569 --- lib/Service/LogService.php | 76 +++++++++++++++++++++++++------------- 1 file changed, 50 insertions(+), 26 deletions(-) diff --git a/lib/Service/LogService.php b/lib/Service/LogService.php index f1febede11..2e2d3e8c8b 100644 --- a/lib/Service/LogService.php +++ b/lib/Service/LogService.php @@ -1,6 +1,6 @@ _auditLogStatement == null) { - // Use the default connection - // audit log should rollback on failure. - $dbh = PdoStorageService::newConnection('default'); - $this->_auditLogStatement = $dbh->prepare(' + $this->prepareAuditLogStatement(); + } + + // If we aren't a string then encode + if (!is_string($object)) { + $object = json_encode($object); + } + + $params = [ + 'logDate' => Carbon::now()->format('U'), + 'userId' => $this->userId, + 'entity' => $entity, + 'message' => $message, + 'entityId' => $entityId, + 'ipAddress' => $this->ipAddress, + 'objectAfter' => $object, + 'sessionHistoryId' => $this->sessionHistoryId, + 'requestId' => $this->requestId + ]; + + try { + $this->_auditLogStatement->execute($params); + } catch (\PDOException $PDOException) { + $errorCode = $PDOException->errorInfo[1] ?? $PDOException->getCode(); + + // Catch 2006 errors (mysql gone away) + if ($errorCode != 2006) { + throw $PDOException; + } else { + $this->prepareAuditLogStatement(); + $this->_auditLogStatement->execute($params); + } + } + + // Although we use the default connection, track audit status separately. + PdoStorageService::incrementStat('audit', 'insert'); + } + + /** + * Helper function to prepare a PDO statement for inserting into the Audit Log. + * sets $_auditLogStatement + * @return void + */ + private function prepareAuditLogStatement(): void + { + // Use the default connection + // audit log should rollback on failure. + $dbh = PdoStorageService::newConnection('default'); + $this->_auditLogStatement = $dbh->prepare(' INSERT INTO `auditlog` ( `logDate`, `userId`, @@ -182,27 +227,6 @@ public function audit($entity, $entityId, $message, $object) :requestId ) '); - } - - // If we aren't a string then encode - if (!is_string($object)) { - $object = json_encode($object); - } - - // Although we use the default connection, track audit status separately. - PdoStorageService::incrementStat('audit', 'insert'); - - $this->_auditLogStatement->execute([ - 'logDate' => Carbon::now()->format('U'), - 'userId' => $this->userId, - 'entity' => $entity, - 'message' => $message, - 'entityId' => $entityId, - 'ipAddress' => $this->ipAddress, - 'objectAfter' => $object, - 'sessionHistoryId' => $this->sessionHistoryId, - 'requestId' => $this->requestId - ]); } /**