summaryrefslogtreecommitdiffstats
path: root/admin/WebConsole3/backend/src/Opengnsys/ServerBundle/Controller/Api/ClientController.php
blob: 8beb6c8304ea8080f33d5a9b790bc4ce3a2e17d9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
<?php

/*
 * This file is part of the Opengnsys Project package.
 *
 * Created by Miguel Angel de Vega on 18/03/16. <miguelangel.devega@sic.com>
 * Copyright (c) 2015 Opengnsys. All rights reserved.
 *
 */
 
namespace Opengnsys\ServerBundle\Controller\Api;

use Opengnsys\ServerBundle\Entity\Client;
use Opengnsys\ServerBundle\Form\Type\ClientType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Form\FormTypeInterface;

use FOS\RestBundle\Controller\Annotations;
use FOS\RestBundle\Controller\Annotations\RouteResource;
use FOS\RestBundle\View\View;
use FOS\RestBundle\Request\ParamFetcherInterface;
use FOS\RestBundle\Context\Context;

use Nelmio\ApiDocBundle\Annotation\ApiDoc;

use Opengnsys\CoreBundle\Exception\InvalidFormException;
use Opengnsys\CoreBundle\Controller\ApiController;

/**
 * @RouteResource("Client")
 */
class ClientController extends ApiController
{	
	
	/**
	 * Options a Client from the submitted data.
	 *
	 * @ApiDoc(
	 *   resource = true,
	 *   description = "Options Client",
	 * )
	 *
	 * @param Request $request the request object
	 *
	 * @return Response
	 */
	public function optionsAction(Request $request)
    {
        $request->setRequestFormat($request->get('_format'));

		$array = array();
		$array['class'] = ClientType::class;
		$array['options'] = array();
		
		$options = $this->container->get('nelmio_api_doc.parser.form_type_parser')->parse($array);
		return $options;
	}
	
	/**
	 * List all Client.
	 *
	 * @ApiDoc(
	 *   resource = true,
	 *   statusCodes = {
	 *     200 = "Returned when successful"
	 *   }
	 * )
	 *
	 * @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\View(templateVar="client", serializerGroups={"opengnsys_server__client_cget"})
	 *
	 * @param Request               $request      the request object
	 * @param ParamFetcherInterface $paramFetcher param fetcher service
	 *
	 * @return array
	 */
	public function cgetAction(Request $request, ParamFetcherInterface $paramFetcher)
	{
        $request->setRequestFormat($request->get('_format'));

		$offset = $paramFetcher->get('offset');
		$offset = null == $offset ? 0 : $offset;
		$limit = $paramFetcher->get('limit');
		
		$matching = $this->filterCriteria($paramFetcher);

        $clientManager = $this->container->get('opengnsys_server.client_manager');

        //$objects = $clientManager->getRepository()->findAll();
		$objects = $clientManager->searchBy($limit, $offset, $matching);

        $groups = array();
        $groups[] = 'opengnsys_server__client_get';
        $groups[] = 'opengnsys_server__repository_cget';
        $groups[] = 'opengnsys_server__hardware_profile_cget';
        $groups[] = 'opengnsys_server__partition_get';
        $groups[] = 'opengnsys_server__netboot_get';

        $response = $this->view($objects);
        $context = new Context();
        $context->addGroups($groups);
        $response->setContext($context);

        return $response;
	}
	
	/**
	 * Get single Client.
	 *
	 * @ApiDoc(
	 *   resource = true,
	 *   description = "Gets a Client for a given id",
	 *   output = "Opengnsys\ServerBundle\Entity\Client",
	 *   statusCodes = {
	 *     200 = "Returned when successful",
	 *     404 = "Returned when the client is not found"
	 *   }
	 * )
	 *
	 * @Annotations\View(templateVar="client", serializerGroups={"opengnsys_server__client_get"})
	 *
	 * @param int     $slug      the client id
	 *
	 * @return array
	 *
	 * @throws NotFoundHttpException when client not exist
	 */
	public function getAction(Request $request, $slug)
	{
        $request->setRequestFormat($request->get('_format'));

		$object = $this->getOr404($slug);

        $groups = array();
        $groups[] = 'opengnsys_server__client_get';
        $groups[] = 'opengnsys_server__repository_cget';
        $groups[] = 'opengnsys_server__hardware_profile_cget';
        $groups[] = 'opengnsys_server__partition_get';
        $groups[] = 'opengnsys_server__netboot_get';

        $response = $this->view($object);
        $context = new Context();
        $context->addGroups($groups);
        $response->setContext($context);

        return $response;
	}
	
	/**
	 * Create a Client from the submitted data.
	 *
	 * @ApiDoc(
	 *   resource = true,
	 *   description = "Creates a new object from the submitted data.",
	 *   input = {"class" = "Opengnsys\ServerBundle\Form\Type\ClientType", "name" = ""},
	 *   statusCodes = {
	 *     200 = "Returned when successful",
	 *     400 = "Returned when the form has errors"
	 *   }
	 * )
	 *
	 * @Annotations\View(
	 *  template = "object",
	 *  serializerGroups={"opengnsys_server__client_get"},
	 *  statusCode = Response::HTTP_CREATED
	 * )
	 *
	 * @param Request $request the request object
	 *
	 * @return FormTypeInterface|View
	 */
	public function cpostAction(Request $request)
	{
        $request->setRequestFormat($request->get('_format'));

	    $parameters = $request->request->all();

        $logger = $this->get('monolog.logger.og_server');
	    $logger->info("----------- NEW CLIENT -----------");
	    foreach ($parameters as $key => $parameter){
            $logger->info($key."=>".$parameter);
        }

		try {
			$object = $this->container->get('opengnsys_server.client_manager')->post($parameters);

            $serviceNetboot = $this->get('opengnsys_service.netboot');
            $serviceNetboot->createBootMode($object);
	
			return $object;
	
		} catch (InvalidFormException $exception) {
	
			return $exception->getForm();
		}
	}
	
	/**
	 * Update existing Client from the submitted data or create a new Client at a specific location.
	 *
	 * @ApiDoc(
	 *   resource = true,
	 *   input = {"class" = "Opengnsys\ServerBundle\Form\Type\ClientType", "name" = ""},
	 *   statusCodes = {
	 *     204 = "Returned when successful",
	 *     400 = "Returned when the form has errors"
	 *   }
	 * )
	 *
	 * @Annotations\View(
	 *  template = "object",
	 *  serializerGroups={"opengnsys_server__client_get"},
	 *  statusCode = Response::HTTP_OK
	 * )
	 *
	 * @param Request $request the request object
	 * @param int     $slug      the client id
	 *
	 * @return FormTypeInterface|View
	 *
	 * @throws NotFoundHttpException when Client not exist
	 */
	public function patchAction(Request $request, $slug)
	{
        $request->setRequestFormat($request->get('_format'));

		try {
			$object = $this->container->get('opengnsys_server.client_manager')->patch(
					$this->getOr404($slug),
					$request->request->all()
			);

            $serviceNetboot = $this->get('opengnsys_service.netboot');
            $serviceNetboot->createBootMode($object);
	
			return $object;
			
		} catch (InvalidFormException $exception) {
	
			return $exception->getForm();
		}
	}
	
	/**
	 * Delete single Client.
	 *
	 * @ApiDoc(
	 *   resource = true,
	 *   description = "Delete a Client for a given id",
	 *   output = "Opengnsys\ServerBundle\Entity\Client",
	 *   statusCodes = {
	 *     200 = "Returned when successful",
	 *     404 = "Returned when the client is not found"
	 *   }
	 * )
	 *
	 * @Annotations\View(templateVar="delete")
	 *
	 * @param int $slug the object id
	 *
	 * @return array
	 *
	 * @throws NotFoundHttpException when object not exist
	 */
	public function deleteAction(Request $request, $slug)
	{
        $request->setRequestFormat($request->get('_format'));

		$object = $this->getOr404($slug);
		
		$object = $this->container->get('opengnsys_server.client_manager')->delete($object);
	
		return $this->view(null, Response::HTTP_NO_CONTENT);
	}

    /**
     * List all Client.
     *
     * @ApiDoc(
     *   resource = true,
     *   statusCodes = {
     *     200 = "Returned when successful"
     *   }
     * )
     *
     * @Annotations\QueryParam(name="clients", nullable=true, description="")
     * @Annotations\QueryParam(name="ou", nullable=true, description="")
     *
     * @Annotations\View(templateVar="client", serializerGroups={""})
     *
     * @param Request               $request      the request object
     * @param ParamFetcherInterface $paramFetcher param fetcher service
     *
     * @return array
     */
    public function statusAction(Request $request, ParamFetcherInterface $paramFetcher)
    {
        $request->setRequestFormat($request->get('_format'));

        $clients = ($paramFetcher->get('clients'))?explode(",",$paramFetcher->get('clients')):null;
        $ou = $paramFetcher->get('ou');


        $clientRepository = $this->container->get('opengnsys_server.client_manager')->getRepository();
        $clients = $clientRepository->searchStatus($clients, $ou);

        return $clients; //$this->view($clients, Response::HTTP_NO_CONTENT);
    }

    /**
     * Create a Client from the submitted data.
     *
     * @ApiDoc(
     *   resource = true,
     *   description = "Creates a new object from the submitted data.",
     *   input = {"class" = "Opengnsys\ServerBundle\Form\Type\ClientStatusType", "name" = ""},
     *   statusCodes = {
     *     200 = "Returned when successful",
     *     400 = "Returned when the form has errors"
     *   }
     * )
     *
     */
    public function postStatusAction(Request $request)
    {
        $request->setRequestFormat($request->get('_format'));

        $logger = $this->get('monolog.logger.og_server');
        $clientManager = $this->container->get('opengnsys_server.client_manager');
        $clientRepository = $clientManager->getRepository();


        $data = $request->request->all();
        $ip = $data['ip'];
        $status = $data['status'];

        $logger->info("----------- CLIENT STATUS -----------");
        $logger->info("ip: " . $ip);
        $logger->info("status: " . $status);

        $client = $clientRepository->findOneBy(array("ip"=>$ip));
        $client->setStatus($status);
        $clientManager->persist($client);

        return $this->view($client, Response::HTTP_NO_CONTENT);
    }

    /**
     * Create a Client from the submitted data.
     *
     * @ApiDoc(
     *   resource = true,
     *   description = "Creates a new object from the submitted data.",
     *   input = {"class" = "Opengnsys\ServerBundle\Form\Type\ClientConfigType", "name" = ""},
     *   statusCodes = {
     *     200 = "Returned when successful",
     *     400 = "Returned when the form has errors"
     *   }
     * )
     *
     */
    public function postConfigAction(Request $request)
    {
        $request->setRequestFormat($request->get('_format'));

        $logger = $this->get('monolog.logger.og_server');
        $em = $this->getDoctrine()->getManager();
        $clientRepository = $em->getRepository(Client::class);


        $data = $request->request->all();
        $ip = $data['ip'];
        $mac = $data['mac'];
        $config = $data['config'];

        $logger->info("----------- CLIENT CONFIG -----------");
        $logger->info("ip: " . $ip. " - mac: ". $mac." - config: " . $config );

        $client = $clientRepository->findOneBy(array("ip"=>$ip, "mac"=>$mac));

        if (!$client) {
            throw new AccessDeniedHttpException();
        }

        $config = explode(';', $config);

        $serialno = $config[0];
        $client->setSerialno($serialno);

        //$client->setStatus($status);

        //array_shift($config);
        // Quitar el último elemento
        array_pop($config);


        $partitionsCount = count($client->getPartitions());
        $logger->info("Client - Partitions: " . $partitionsCount );
        foreach ($config as $key => $part){
            //$logger->info("key: " . $key. " - part: ". $part );
            $part = explode(':', $part);
            $partition = $client->getPartition($key);
            $partition->setNumDisk($part[0]);
            $partition->setNumPartition($part[1]);
            $partition->setPartitionCode($part[2]);
            $partition->setFilesystem($part[3]);
            $partition->setOsName($part[4]);
            $partition->setSize(intval(($part[5]=='')?'0':$part[5]));
            $partition->setUsage(floatval(($part[6]=='')?'0':$part[6]));

            $logger->info("PARTITION ADD/UPDATE - key: ".$key." - id: " . $partition->getId(). " - disk". $partition->getNumDisk(). " - partition ".$partition->getNumPartition(). "  - filesystem: ".$partition->getFilesystem() );

            // Si el Filesystem / PartitionCode es Cache leer la información del contenido de la cache.
            if($partition->getFilesystem() === "CACHE"){
                $path = $this->container->getParameter('path_client');
                $file = $ip.".cache.txt";
                $filePath = $path.$file;
                if(file_exists($filePath)) {

                    $data = file_get_contents($filePath);
                    /*
                    $data = explode("\n",trim($data));
                    unset($data[0]);
                    foreach ($data as $item){
                        $type = array_key_exists(0, $item)?trim($item[0]):"";
                        $description = array_key_exists(1, $item)?trim($item[1]):"";
                        if($type!= "" && $description != ""){
                            $logger->info("Hardware: ".$type." = ".$description);
                        }
                    }
                    */
                    $partition->setCacheContent($data);
                }
            }
            $em->persist($partition);
        }
        // Borrar las particiones que ya no existe
        for($index = $key+1; $index < $partitionsCount; $index++){
            $partition = $client->getPartition($index);
            $em->remove($partition);
            $logger->info("PARTITION REMOVE - key: ". $index." - id: " . $partition->getId(). " - disk". $partition->getNumDisk(). " - partition ".$partition->getNumPartition(). "  - filesystem: ".$partition->getFilesystem() );
        }

        $em->flush();

        return $this->view($client, Response::HTTP_NO_CONTENT);

    }
	
	/**
	 * Fetch a Client or throw an 404 Exception.
	 *
	 * @param mixed $slug
	 *
	 * @return Client
	 *
	 * @throws NotFoundHttpException
	 */
	protected function getOr404($slug)
	{
		if (!($object = $this->container->get('opengnsys_server.client_manager')->get($slug))) {
			throw new NotFoundHttpException(sprintf('The resource \'%s\' was not found.',$slug));
		}
	
		return $object;
	}
}