From 9709c56f87eb2bd2831b1967ca24f23988d4565d Mon Sep 17 00:00:00 2001 From: devega Date: Fri, 24 May 2019 15:04:09 +0200 Subject: - Corrección en el envío de los comandos - Nuevo end-point para matar procesos MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Controller/Api/CommandController.php | 92 +---------------- .../Controller/Api/TraceController.php | 76 ++++++++++++-- .../Entity/Repository/SoftwareRepository.php | 6 +- .../Entity/Repository/TraceRepository.php | 10 ++ .../Resources/config/doctrine/Partition.orm.xml | 2 +- .../ServerBundle/Resources/config/services.yml | 3 + .../Opengnsys/ServerBundle/Service/CurlService.php | 109 +++++++++++++++++++++ 7 files changed, 198 insertions(+), 100 deletions(-) create mode 100644 admin/WebConsole3/backend/src/Opengnsys/ServerBundle/Service/CurlService.php diff --git a/admin/WebConsole3/backend/src/Opengnsys/ServerBundle/Controller/Api/CommandController.php b/admin/WebConsole3/backend/src/Opengnsys/ServerBundle/Controller/Api/CommandController.php index 7873fc06..b5270a96 100644 --- a/admin/WebConsole3/backend/src/Opengnsys/ServerBundle/Controller/Api/CommandController.php +++ b/admin/WebConsole3/backend/src/Opengnsys/ServerBundle/Controller/Api/CommandController.php @@ -289,7 +289,8 @@ class CommandController extends ApiController $em->persist($trace); $em->flush(); - $result = $this->sendCurl($client,$script,$trace,$sendConfig); + $curlService = $this->get("opengnsys_service.curl"); + $result = $curlService->sendCurl("script", $trace, $script, $sendConfig); $outputs[] = $result; if($result["error"] != ""){ @@ -320,95 +321,6 @@ class CommandController extends ApiController return $this->view($outputs, $response); } - private function sendCurl($client, $script, $trace, $sendConfig) - { - $logger = $this->get('monolog.logger.og_server'); - - $ip = $client->getIp(); - $agentToken = $client->getAgentToken(); - - //$url = "https://".$ip."cgi-bin/api/LogCommand.sh"; - $url = "https://".$ip.":8000/opengnsys/script"; - $redirectUri = $this->generateUrl('opengnsys_server__api_post_traces', array(), UrlGeneratorInterface::ABSOLUTE_URL); - - $arrayToPost = array( - 'id' => $trace->getId(), - 'script' => base64_encode($script), - 'ip' => $ip, - 'sendConfig'=> $sendConfig, - 'redirectUri' => $redirectUri - ); // this will be json_encode. If you don't want to json_encode, use HttpPostJson instead of HttpPostJsonBody - - $headers[] = "Authorization: ".$agentToken; - - //$postUrl = http_build_query ($arrayToPost); - $postUrl = json_encode ($arrayToPost); - - //$postUrl = base64_encode ($postUrl); //json_encode($arrayToPost); - - $logger->info("SEND CURL url: " . $url); - $logger->info("SEND CURL id: " . $trace->getId()); - $logger->info("SEND CURL script: " . $script); - $logger->info("SEND CURL ip: " . $ip); - $logger->info("SEND CURL token: " . $agentToken); - $logger->info("SEND CURL redirect_uri: " . $redirectUri); - $logger->info("SEND CURL postUrl: " .$postUrl); - - // _GET - //$url = $url."?".$postUrl; - - // abrimos la sesión cURL - $ch = curl_init(); - - // definimos la URL a la que hacemos la petición - curl_setopt($ch, CURLOPT_URL,$url); - - curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); - - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); - curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); - - // _POST_ - curl_setopt($ch, CURLOPT_POST, true); // indicamos el tipo de petición: POST - // definimos cada uno de los parámetros - curl_setopt($ch, CURLOPT_POSTFIELDS, $postUrl); - - // recibimos la respuesta y la guardamos en una variable - curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); - - curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); // The number of seconds to wait while trying to connect. Use 0 to wait indefinitely. - curl_setopt($ch, CURLOPT_TIMEOUT, 20); //timeout in seconds - - $remote_server_output = curl_exec ($ch); - $remote_server_error = ""; - - $logger->info("SEND CURL output: " . $remote_server_output); - - if (curl_errno($ch)) { - // this would be your first hint that something went wrong - $remote_server_error = curl_error($ch); - $logger->info("SEND CURL error: ". $remote_server_error); - - $em = $this->getDoctrine()->getManager(); - $client->setStatus("off"); - $em->flush(); - } - - $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); - $logger->info("SEND CURL status code: ". $statusCode); - - // cerramos la sesión cURL - curl_close ($ch); - - $output['id'] = $client->getId(); - $output['name'] = $client->getName(); - $output['statusCode'] = $statusCode; - $output['output'] = $remote_server_output; - $output['error'] = $remote_server_error; - - return $output; - } - /** * Delete single Command. * diff --git a/admin/WebConsole3/backend/src/Opengnsys/ServerBundle/Controller/Api/TraceController.php b/admin/WebConsole3/backend/src/Opengnsys/ServerBundle/Controller/Api/TraceController.php index 6692176a..388c3955 100644 --- a/admin/WebConsole3/backend/src/Opengnsys/ServerBundle/Controller/Api/TraceController.php +++ b/admin/WebConsole3/backend/src/Opengnsys/ServerBundle/Controller/Api/TraceController.php @@ -77,6 +77,8 @@ class TraceController extends ApiController * @Annotations\QueryParam(name="offset", requirements="\d+", nullable=true, description="Offset from which to start listing objects.") * @Annotations\QueryParam(name="limit", requirements="\d+", nullable=true, description="How many objects to return.") * @Annotations\QueryParam(name="finished", requirements="0|1", nullable=true, description="How many objects to return.") + * @Annotations\QueryParam(name="fromDate", requirements="[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])", nullable=true, description="Date start where search. (yyyy-mm-dd)") + * @Annotations\QueryParam(name="toDate", requirements="[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])", nullable=true, description="Date end where search. (yyyy-mm-dd)") * * @Annotations\View(templateVar="objects", serializerGroups={"opengnsys_server__trace_cget"}) * @@ -97,7 +99,9 @@ class TraceController extends ApiController $em = $this->getDoctrine()->getManager(); $repository = $em->getRepository(Trace::class); - $objects = $repository->searchBy($matching, [], $limit, $offset); //findBy(array("status"=>null), array(), $limit, $offset); + $ordered = ["executedAt" => "DESC"]; + + $objects = $repository->searchBy($matching, $ordered, $limit, $offset); $groups = array(); $groups[] = 'opengnsys_server__client_cget'; @@ -181,7 +185,7 @@ class TraceController extends ApiController $hardwareProfileRepository = $em->getRepository(HardwareProfile::class); $logger->info("-> HARDWARE_INVENTORY <-"); - //$path = $this->getParameter('path_client'); + //$path = $this->container->getParameter('path_client'); if($client != null){ //$ip = $client->getIp(); @@ -265,7 +269,7 @@ class TraceController extends ApiController $image->setRevision($image->getRevision() + 1); $image->setPartitionInfo(json_encode($partitionInfo)); - $path = $this->getParameter('path_images'); + $path = $this->container->getParameter('path_images'); $file = $canonicalName.".img"; $filePath = $path.$file; @@ -294,7 +298,7 @@ class TraceController extends ApiController $partitionRepository = $em->getRepository(Partition::class); $logger->info("-> SOFTWARE_INVENTORY <-"); - //$path = $this->getParameter('path_client'); + //$path = $this->container->getParameter('path_client'); if($client != null){ //$ip = $client->getIp(); @@ -398,8 +402,6 @@ class TraceController extends ApiController * } * ) * - * @Annotations\View(templateVar="delete") - * * @param int $slug the object id * * @return array @@ -421,4 +423,66 @@ class TraceController extends ApiController return $this->view(null, Response::HTTP_NO_CONTENT); } + + /** + * Stop single Trace. + * + * @ApiDoc( + * resource = true, + * description = "Stop a Trace for a given id", + * output = "Opengnsys\ServerBundle\Entity\Trace", + * statusCodes = { + * 200 = "Returned when successful", + * 404 = "Returned when the client is not found" + * } + * ) + * + * @param int $slug the object id + * + * @return array + * + * @throws NotFoundHttpException when object not exist + */ + public function postStopAction(Request $request, $slug) + { + $request->setRequestFormat($request->get('_format')); + + $logger = $this->get('monolog.logger.og_server'); + $logger->info("----------- TRACE STOP -----------"); + + $em = $this->getDoctrine()->getManager(); + $traceRepository = $em->getRepository(Trace::class); + + + if (!($object = $traceRepository->find($slug))) { + throw new NotFoundHttpException(sprintf('The resource \'%s\' was not found.',$slug)); + } + + $trace = $object; + $script = ""; + $sendConfig = ""; + + $curlService = $this->get("opengnsys_service.curl"); + $result = $curlService->sendCurl("stopcmd", $trace, $script, $sendConfig); + + //$object-> + + + if($result["error"] != ""){ + $logger->info("trace with errors"); + $trace->setError($result["error"]); + $trace->setOutput($result["output"]); + $trace->setFinishedAt(new \DateTime()); + $trace->setStatus(-1); + $em->flush(); + } + + + $em->flush(); + + return $this->view(null, Response::HTTP_NO_CONTENT); + } + + + } diff --git a/admin/WebConsole3/backend/src/Opengnsys/ServerBundle/Entity/Repository/SoftwareRepository.php b/admin/WebConsole3/backend/src/Opengnsys/ServerBundle/Entity/Repository/SoftwareRepository.php index 6fe4be8d..eb94d0fa 100644 --- a/admin/WebConsole3/backend/src/Opengnsys/ServerBundle/Entity/Repository/SoftwareRepository.php +++ b/admin/WebConsole3/backend/src/Opengnsys/ServerBundle/Entity/Repository/SoftwareRepository.php @@ -27,14 +27,14 @@ class SoftwareRepository extends BaseRepository if(count($selects) > 0){ $qb = $this->createSelect($qb, $selects); }else{ - $qb->select("DISTINCT o.createdAt, o.updatedAt, o.notes, o.description, o.osType, o.type, o.id"); + $qb->select("DISTINCT o.createdAt, o.updatedAt, o.notes, o.description, o.type, o.id"); } if($term != ""){ if(count($searchs) > 0){ $qb = $this->createSearch($qb, $term, $searchs); }else{ - $qb->andWhere("o.createdAt LIKE :term OR o.updatedAt LIKE :term OR o.notes LIKE :term OR o.description LIKE :term OR o.osType LIKE :term OR o.type LIKE :term OR o.id LIKE :term ")->setParameter('term', '%' . $term . '%'); + $qb->andWhere("o.createdAt LIKE :term OR o.updatedAt LIKE :term OR o.notes LIKE :term OR o.description LIKE :term OR OR o.type LIKE :term OR o.id LIKE :term ")->setParameter('term', '%' . $term . '%'); } } @@ -64,7 +64,7 @@ class SoftwareRepository extends BaseRepository if(count($searchs) > 0){ $qb = $this->createSearch($qb, $term, $searchs); }else{ - $qb->andWhere("o.createdAt LIKE :term OR o.updatedAt LIKE :term OR o.notes LIKE :term OR o.description LIKE :term OR o.osType LIKE :term OR o.type LIKE :term OR o.id LIKE :term ")->setParameter('term', '%' . $term . '%'); + $qb->andWhere("o.createdAt LIKE :term OR o.updatedAt LIKE :term OR o.notes LIKE :term OR o.description LIKE :term OR o.type LIKE :term OR o.id LIKE :term ")->setParameter('term', '%' . $term . '%'); } } diff --git a/admin/WebConsole3/backend/src/Opengnsys/ServerBundle/Entity/Repository/TraceRepository.php b/admin/WebConsole3/backend/src/Opengnsys/ServerBundle/Entity/Repository/TraceRepository.php index f3d8c02f..3e0fbc75 100644 --- a/admin/WebConsole3/backend/src/Opengnsys/ServerBundle/Entity/Repository/TraceRepository.php +++ b/admin/WebConsole3/backend/src/Opengnsys/ServerBundle/Entity/Repository/TraceRepository.php @@ -107,6 +107,16 @@ class TraceRepository extends BaseRepository unset($matching['finished']); } + if(array_key_exists("fromDate", $matching) && $matching['fromDate'] != null){ + $qb->andWhere("o.executedAt >= :fromDate")->setParameter("fromDate", $matching['fromDate']); + } + unset($matching['fromDate']); + + if(array_key_exists("toDate", $matching) && $matching['toDate'] != null){ + $qb->andWhere("o.executedAt <= :toDate")->setParameter("toDate", $matching['toDate']); + } + unset($matching['toDate']); + $qb = parent::createMaching($qb, $matching); return $qb; diff --git a/admin/WebConsole3/backend/src/Opengnsys/ServerBundle/Resources/config/doctrine/Partition.orm.xml b/admin/WebConsole3/backend/src/Opengnsys/ServerBundle/Resources/config/doctrine/Partition.orm.xml index 751b4dad..e79262e5 100644 --- a/admin/WebConsole3/backend/src/Opengnsys/ServerBundle/Resources/config/doctrine/Partition.orm.xml +++ b/admin/WebConsole3/backend/src/Opengnsys/ServerBundle/Resources/config/doctrine/Partition.orm.xml @@ -25,7 +25,7 @@ - + diff --git a/admin/WebConsole3/backend/src/Opengnsys/ServerBundle/Resources/config/services.yml b/admin/WebConsole3/backend/src/Opengnsys/ServerBundle/Resources/config/services.yml index 4d648733..1a90cce8 100644 --- a/admin/WebConsole3/backend/src/Opengnsys/ServerBundle/Resources/config/services.yml +++ b/admin/WebConsole3/backend/src/Opengnsys/ServerBundle/Resources/config/services.yml @@ -19,6 +19,9 @@ services: opengnsys_service.netboot: class: Opengnsys\ServerBundle\Service\NetbootService arguments: ["%pxedir%", '@doctrine.orm.entity_manager'] + opengnsys_service.curl: + class: Opengnsys\ServerBundle\Service\CurlService + arguments: ['@doctrine.orm.entity_manager', '@router', '@monolog.logger.og_server'] # MANAGER opengnsys_server.client_manager: diff --git a/admin/WebConsole3/backend/src/Opengnsys/ServerBundle/Service/CurlService.php b/admin/WebConsole3/backend/src/Opengnsys/ServerBundle/Service/CurlService.php new file mode 100644 index 00000000..078124ec --- /dev/null +++ b/admin/WebConsole3/backend/src/Opengnsys/ServerBundle/Service/CurlService.php @@ -0,0 +1,109 @@ +em = $em; + $this->router = $router; + $this->logger = $logger; + } + + public function sendCurl($url, $trace, $script, $sendConfig) + { + $client = $trace->getClient(); + + $ip = $client->getIp(); + $agentToken = $client->getAgentToken(); + $url = "https://".$ip.":8000/opengnsys/".$url; + + $redirectUri = $this->router->generate('opengnsys_server__api_post_traces', array(), UrlGeneratorInterface::ABSOLUTE_URL); + + $arrayToPost = array( + 'id' => $trace->getId(), + 'script' => base64_encode( $script), + 'ip' => $ip, + 'sendConfig'=> ($sendConfig)?"true":"false", + 'redirectUri' => $redirectUri + ); // this will be json_encode. If you don't want to json_encode, use HttpPostJson instead of HttpPostJsonBody + + $headers[] = "Authorization: ".$agentToken; + + //$postUrl = http_build_query ($arrayToPost); + $postUrl = json_encode ($arrayToPost); + + //$postUrl = base64_encode ($postUrl); //json_encode($arrayToPost); + + $this->logger->info("SEND CURL url: " . $url); + $this->logger->info("SEND CURL id: " . $trace->getId()); + $this->logger->info("SEND CURL script: " . $script); + $this->logger->info("SEND CURL ip: " . $ip); + $this->logger->info("SEND CURL token: " . $agentToken); + $this->logger->info("SEND CURL redirect_uri: " . $redirectUri); + $this->logger->info("SEND CURL postUrl: " .$postUrl); + + // _GET + //$url = $url."?".$postUrl; + + // abrimos la sesión cURL + $ch = curl_init(); + + // definimos la URL a la que hacemos la petición + curl_setopt($ch, CURLOPT_URL,$url); + + curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); + + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); + + // _POST_ + curl_setopt($ch, CURLOPT_POST, true); // indicamos el tipo de petición: POST + // definimos cada uno de los parámetros + curl_setopt($ch, CURLOPT_POSTFIELDS, $postUrl); + + // recibimos la respuesta y la guardamos en una variable + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + + curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); // The number of seconds to wait while trying to connect. Use 0 to wait indefinitely. + curl_setopt($ch, CURLOPT_TIMEOUT, 20); //timeout in seconds + + $remote_server_output = curl_exec ($ch); + $remote_server_error = ""; + + $this->logger->info("SEND CURL output: " . $remote_server_output); + + if (curl_errno($ch)) { + // this would be your first hint that something went wrong + $remote_server_error = curl_error($ch); + $this->logger->info("SEND CURL error: ". $remote_server_error); + + $client->setStatus("off"); + $this->em->flush(); + } + + $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); + $this->logger->info("SEND CURL status code: ". $statusCode); + + // cerramos la sesión cURL + curl_close ($ch); + + $output['id'] = $client->getId(); + $output['name'] = $client->getName(); + $output['statusCode'] = $statusCode; + $output['output'] = $remote_server_output; + $output['error'] = $remote_server_error; + + return $output; + } +} -- cgit v1.2.3-18-g5258