Commit 8207a89e52d75fda8c13850839b80853b38b4579

Authored by Eduardo Santos
1 parent ffdf73eb
Exists in master and in 2 other branches 3,1, 3.1

Adiciona inserção da impressora via PUT no Cocar

Controller/ApiController.php 0 → 100644
... ... @@ -0,0 +1,133 @@
  1 +<?php
  2 +/**
  3 + * Created by PhpStorm.
  4 + * User: eduardo
  5 + * Date: 14/10/14
  6 + * Time: 01:36
  7 + */
  8 +
  9 +namespace Swpb\Bundle\CocarBundle\Controller;
  10 +
  11 +use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  12 +use Symfony\Component\HttpFoundation\Request;
  13 +use Symfony\Component\HttpFoundation\JsonResponse;
  14 +use Swpb\Bundle\CocarBundle\Entity\PrinterCounter;
  15 +use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
  16 +use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
  17 +
  18 +
  19 +/**
  20 + * Class ApiController
  21 + * @package Swpb\Bundle\CocarBundle\Controller
  22 + *
  23 + * @Route("/api")
  24 + */
  25 +class ApiController extends Controller {
  26 +
  27 + /**
  28 + * @Route("/login", name="api_login")
  29 + * @Method("POST")
  30 + * Faz login do agente do Cocar
  31 + */
  32 + public function loginAction(Request $request)
  33 + {
  34 + $logger = $this->get('logger');
  35 + $em = $this->getDoctrine()->getManager();
  36 + $data = $request->getContent();
  37 +
  38 + $session = $request->getSession();
  39 + $session->start();
  40 +
  41 + $chavecrip = '123456';
  42 +
  43 + $usuario = $this->get('security.context')->getToken()->getUser();
  44 + $logger->debug("Usuario encontrado: ".$usuario->getUserName());
  45 +
  46 + $auth = new JsonResponse();
  47 + $auth->setContent(json_encode(array(
  48 + 'session' => $session->getId(),
  49 + 'chavecrip' => $usuario->getApiKey()
  50 + )));
  51 +
  52 + return $auth;
  53 + }
  54 +
  55 + /**
  56 + * @param $ip_addr
  57 + * @Route("/printer/{ip_addr}", name="printer_counter_update")
  58 + * @Method("PUT")
  59 + */
  60 + public function printerAction($ip_addr, Request $request) {
  61 + $em = $this->getDoctrine()->getManager();
  62 + $logger = $this->get('logger');
  63 +
  64 + $status = $request->getContent();
  65 + $dados = json_decode($status, true);
  66 +
  67 + if (empty($dados)) {
  68 + $logger->error("JSON INVÁLIDO!!!!!!!!!!!!!!!!!!! Erro no envio das informações da impressora $ip_addr");
  69 + // Retorna erro se o JSON for inválido
  70 + $error_msg = '{
  71 + "message": "JSON Inválido",
  72 + "codigo": 1
  73 + }';
  74 +
  75 +
  76 + $response = new JsonResponse();
  77 + $response->setStatusCode('500');
  78 + $response->setContent($error_msg);
  79 + return $response;
  80 + }
  81 +
  82 + $logger->debug("Atualizando informações para a impressora com IP = $ip_addr\n".$status);
  83 +
  84 + try {
  85 + $printer = $em->getRepository('CocarBundle:Printer')->findOneBy(array('host' => $ip_addr));
  86 + }
  87 + catch(\Doctrine\ORM\NoResultException $e) {
  88 + $logger->error("COLETA: Impressora não cadastrada: $ip_addr \n$e");
  89 + $error_msg = '{
  90 + "message": "Impressora não cadastrada",
  91 + "codigo": 2
  92 + }';
  93 +
  94 +
  95 + $response = new JsonResponse();
  96 + $response->setStatusCode('500');
  97 + $response->setContent($error_msg);
  98 + return $response;
  99 + }
  100 +
  101 +
  102 + $counter = $this->getDoctrine()->getManager()->getRepository('CocarBundle:PrinterCounter')->findBy(array(
  103 + 'printer' => $printer,
  104 + 'date' => $dados['counter_time']
  105 + ));
  106 +
  107 + if(empty($counter)) {
  108 + $counter = new PrinterCounter;
  109 + } else {
  110 + $this->get('logger')->error("Entrada repetida para impressora $printer e data ".$dados['counter_time']);
  111 + return true;
  112 + }
  113 +
  114 + // Atualiza impressora sempre que alterar o serial
  115 + $printer->setName($dados['model']);
  116 + $printer->setSerie($dados['serial']);
  117 + $printer->setDescription($dados['description']);
  118 +
  119 + // Grava o contador
  120 + $counter->setPrinter($printer);
  121 + $counter->setPrints($dados['counter']);
  122 + $counter->setDate($dados['counter_time']);
  123 +
  124 + $em->persist($printer);
  125 + $em->persist($counter);
  126 + $em->flush();
  127 +
  128 + $response = new JsonResponse();
  129 + $response->setStatusCode('200');
  130 + return $response;
  131 + }
  132 +
  133 +}
0 134 \ No newline at end of file
... ...
Controller/PrinterController.php
... ... @@ -612,13 +612,13 @@ class PrinterController extends Controller
612 612 {
613 613 $n_printers = $this->em->createQuery('SELECT count(p) FROM CocarBundle:Printer p')->getSingleScalarResult();
614 614  
615   - $limit = 500;
  615 + $limit = 20;
616 616 $iterations = (int)($n_printers / $limit);
617 617 $iterations = $iterations + 1;
618 618  
619 619 $i = 0;
620 620 while ($i < $iterations) {
621   - // O objetivo é executar a coleta a cada 1000 impressoras
  621 + // O objetivo é executar a coleta a cada $limit impressoras
622 622 $offset = $limit * $i;
623 623 $this->selectPrinters($limit, $offset);
624 624 $i = $i + 1;
... ... @@ -653,9 +653,12 @@ class PrinterController extends Controller
653 653 $community = $printer->getCommunitySnmpPrinter();
654 654 $host = $printer->getHost();
655 655  
656   - $this->get('logger')->info("Coletando impressora $host | ID ".$printer->getId());
  656 + $this->get('logger')->info("Coletando impressora $host | ID ".$printer->getId());
  657 + $arrBundle = $this->get('kernel')->getBundles();
  658 + $rootDir = $arrBundle['CocarBundle']->getPath();
  659 + $script = $rootDir . "/Resources/scripts/timeout3";
657 660  
658   - $com = "snmpwalk -O qv -v 1 -c $community $host 1.3.6.1.2.1.43.10.2.1.4.1.1";
  661 + $com = "$script snmpwalk -O qv -v 1 -c $community $host 1.3.6.1.2.1.43.10.2.1.4.1.1";
659 662  
660 663 if($outPut = shell_exec($com))
661 664 {
... ...
Resources/scripts/timeout3 0 → 100755
... ... @@ -0,0 +1,91 @@
  1 +#!/bin/bash
  2 +#
  3 +# The Bash shell script executes a command with a time-out.
  4 +# Upon time-out expiration SIGTERM (15) is sent to the process. If the signal
  5 +# is blocked, then the subsequent SIGKILL (9) terminates it.
  6 +#
  7 +# Based on the Bash documentation example.
  8 +
  9 +# Hello Chet,
  10 +# please find attached a "little easier" :-) to comprehend
  11 +# time-out example. If you find it suitable, feel free to include
  12 +# anywhere: the very same logic as in the original examples/scripts, a
  13 +# little more transparent implementation to my taste.
  14 +#
  15 +# Dmitry V Golovashkin <Dmitry.Golovashkin@sas.com>
  16 +
  17 +scriptName="${0##*/}"
  18 +
  19 +declare -i DEFAULT_TIMEOUT=9
  20 +declare -i DEFAULT_INTERVAL=1
  21 +declare -i DEFAULT_DELAY=1
  22 +
  23 +# Timeout.
  24 +declare -i timeout=DEFAULT_TIMEOUT
  25 +# Interval between checks if the process is still alive.
  26 +declare -i interval=DEFAULT_INTERVAL
  27 +# Delay between posting the SIGTERM signal and destroying the process by SIGKILL.
  28 +declare -i delay=DEFAULT_DELAY
  29 +
  30 +function printUsage() {
  31 + cat <<EOF
  32 +
  33 +Synopsis
  34 + $scriptName [-t timeout] [-i interval] [-d delay] command
  35 + Execute a command with a time-out.
  36 + Upon time-out expiration SIGTERM (15) is sent to the process. If SIGTERM
  37 + signal is blocked, then the subsequent SIGKILL (9) terminates it.
  38 +
  39 + -t timeout
  40 + Number of seconds to wait for command completion.
  41 + Default value: $DEFAULT_TIMEOUT seconds.
  42 +
  43 + -i interval
  44 + Interval between checks if the process is still alive.
  45 + Positive integer, default value: $DEFAULT_INTERVAL seconds.
  46 +
  47 + -d delay
  48 + Delay between posting the SIGTERM signal and destroying the
  49 + process by SIGKILL. Default value: $DEFAULT_DELAY seconds.
  50 +
  51 +As of today, Bash does not support floating point arithmetic (sleep does),
  52 +therefore all delay/time values must be integers.
  53 +EOF
  54 +}
  55 +
  56 +# Options.
  57 +while getopts ":t:i:d:" option; do
  58 + case "$option" in
  59 + t) timeout=$OPTARG ;;
  60 + i) interval=$OPTARG ;;
  61 + d) delay=$OPTARG ;;
  62 + *) printUsage; exit 1 ;;
  63 + esac
  64 +done
  65 +shift $((OPTIND - 1))
  66 +
  67 +# $# should be at least 1 (the command to execute), however it may be strictly
  68 +# greater than 1 if the command itself has options.
  69 +if (($# == 0 || interval <= 0)); then
  70 + printUsage
  71 + exit 1
  72 +fi
  73 +
  74 +# kill -0 pid Exit code indicates if a signal may be sent to $pid process.
  75 +(
  76 + ((t = timeout))
  77 +
  78 + while ((t > 0)); do
  79 + sleep $interval
  80 + kill -0 $$ || exit 0
  81 + ((t -= interval))
  82 + done
  83 +
  84 + # Be nice, post SIGTERM first.
  85 + # The 'exit 0' below will be executed if any preceeding command fails.
  86 + kill -s SIGTERM $$ && kill -0 $$ || exit 0
  87 + sleep $delay
  88 + kill -s SIGKILL $$
  89 +) 2> /dev/null &
  90 +
  91 +exec "$@"
... ...