diff --git a/Controller/ApiController.php b/Controller/ApiController.php new file mode 100644 index 0000000..f34ab85 --- /dev/null +++ b/Controller/ApiController.php @@ -0,0 +1,133 @@ +get('logger'); + $em = $this->getDoctrine()->getManager(); + $data = $request->getContent(); + + $session = $request->getSession(); + $session->start(); + + $chavecrip = '123456'; + + $usuario = $this->get('security.context')->getToken()->getUser(); + $logger->debug("Usuario encontrado: ".$usuario->getUserName()); + + $auth = new JsonResponse(); + $auth->setContent(json_encode(array( + 'session' => $session->getId(), + 'chavecrip' => $usuario->getApiKey() + ))); + + return $auth; + } + + /** + * @param $ip_addr + * @Route("/printer/{ip_addr}", name="printer_counter_update") + * @Method("PUT") + */ + public function printerAction($ip_addr, Request $request) { + $em = $this->getDoctrine()->getManager(); + $logger = $this->get('logger'); + + $status = $request->getContent(); + $dados = json_decode($status, true); + + if (empty($dados)) { + $logger->error("JSON INVÁLIDO!!!!!!!!!!!!!!!!!!! Erro no envio das informações da impressora $ip_addr"); + // Retorna erro se o JSON for inválido + $error_msg = '{ + "message": "JSON Inválido", + "codigo": 1 + }'; + + + $response = new JsonResponse(); + $response->setStatusCode('500'); + $response->setContent($error_msg); + return $response; + } + + $logger->debug("Atualizando informações para a impressora com IP = $ip_addr\n".$status); + + try { + $printer = $em->getRepository('CocarBundle:Printer')->findOneBy(array('host' => $ip_addr)); + } + catch(\Doctrine\ORM\NoResultException $e) { + $logger->error("COLETA: Impressora não cadastrada: $ip_addr \n$e"); + $error_msg = '{ + "message": "Impressora não cadastrada", + "codigo": 2 + }'; + + + $response = new JsonResponse(); + $response->setStatusCode('500'); + $response->setContent($error_msg); + return $response; + } + + + $counter = $this->getDoctrine()->getManager()->getRepository('CocarBundle:PrinterCounter')->findBy(array( + 'printer' => $printer, + 'date' => $dados['counter_time'] + )); + + if(empty($counter)) { + $counter = new PrinterCounter; + } else { + $this->get('logger')->error("Entrada repetida para impressora $printer e data ".$dados['counter_time']); + return true; + } + + // Atualiza impressora sempre que alterar o serial + $printer->setName($dados['model']); + $printer->setSerie($dados['serial']); + $printer->setDescription($dados['description']); + + // Grava o contador + $counter->setPrinter($printer); + $counter->setPrints($dados['counter']); + $counter->setDate($dados['counter_time']); + + $em->persist($printer); + $em->persist($counter); + $em->flush(); + + $response = new JsonResponse(); + $response->setStatusCode('200'); + return $response; + } + +} \ No newline at end of file diff --git a/Controller/PrinterController.php b/Controller/PrinterController.php index 74183e1..89b679d 100755 --- a/Controller/PrinterController.php +++ b/Controller/PrinterController.php @@ -612,13 +612,13 @@ class PrinterController extends Controller { $n_printers = $this->em->createQuery('SELECT count(p) FROM CocarBundle:Printer p')->getSingleScalarResult(); - $limit = 500; + $limit = 20; $iterations = (int)($n_printers / $limit); $iterations = $iterations + 1; $i = 0; while ($i < $iterations) { - // O objetivo é executar a coleta a cada 1000 impressoras + // O objetivo é executar a coleta a cada $limit impressoras $offset = $limit * $i; $this->selectPrinters($limit, $offset); $i = $i + 1; @@ -653,9 +653,12 @@ class PrinterController extends Controller $community = $printer->getCommunitySnmpPrinter(); $host = $printer->getHost(); - $this->get('logger')->info("Coletando impressora $host | ID ".$printer->getId()); + $this->get('logger')->info("Coletando impressora $host | ID ".$printer->getId()); + $arrBundle = $this->get('kernel')->getBundles(); + $rootDir = $arrBundle['CocarBundle']->getPath(); + $script = $rootDir . "/Resources/scripts/timeout3"; - $com = "snmpwalk -O qv -v 1 -c $community $host 1.3.6.1.2.1.43.10.2.1.4.1.1"; + $com = "$script snmpwalk -O qv -v 1 -c $community $host 1.3.6.1.2.1.43.10.2.1.4.1.1"; if($outPut = shell_exec($com)) { diff --git a/Resources/scripts/timeout3 b/Resources/scripts/timeout3 new file mode 100755 index 0000000..5c19d2e --- /dev/null +++ b/Resources/scripts/timeout3 @@ -0,0 +1,91 @@ +#!/bin/bash +# +# The Bash shell script executes a command with a time-out. +# Upon time-out expiration SIGTERM (15) is sent to the process. If the signal +# is blocked, then the subsequent SIGKILL (9) terminates it. +# +# Based on the Bash documentation example. + +# Hello Chet, +# please find attached a "little easier" :-) to comprehend +# time-out example. If you find it suitable, feel free to include +# anywhere: the very same logic as in the original examples/scripts, a +# little more transparent implementation to my taste. +# +# Dmitry V Golovashkin + +scriptName="${0##*/}" + +declare -i DEFAULT_TIMEOUT=9 +declare -i DEFAULT_INTERVAL=1 +declare -i DEFAULT_DELAY=1 + +# Timeout. +declare -i timeout=DEFAULT_TIMEOUT +# Interval between checks if the process is still alive. +declare -i interval=DEFAULT_INTERVAL +# Delay between posting the SIGTERM signal and destroying the process by SIGKILL. +declare -i delay=DEFAULT_DELAY + +function printUsage() { + cat < 0)); do + sleep $interval + kill -0 $$ || exit 0 + ((t -= interval)) + done + + # Be nice, post SIGTERM first. + # The 'exit 0' below will be executed if any preceeding command fails. + kill -s SIGTERM $$ && kill -0 $$ || exit 0 + sleep $delay + kill -s SIGKILL $$ +) 2> /dev/null & + +exec "$@" -- libgit2 0.21.2