source: admin/WebConsole/uds-set-service-pool.php @ fbcfc55

configure-oglivelgromero-new-oglivemainmaint-cronmount-efivarfsmultivmmultivm-ogboot-installerogClonningEngineoglive-ipv6test-python-scriptsticket-301ticket-50ticket-50-oldticket-577ticket-585ticket-611ticket-612ticket-693ticket-700ubu24tplunification2use-local-agent-oglivevarios-instalacion
Last change on this file since fbcfc55 was 23f2b49, checked in by Natalia Serrano <natalia.serrano@…>, 14 months ago

refs #235 Add finer adjustments

  • Remove duplicated variable $tz
  • Move UDS-related vars to their own file for inclusion
  • Put a displace comment in its place
  • Property mode set to 100644
File size: 14.3 KB
Line 
1<?php
2// ********************************************************************
3// Author: Juan Manuel Bardallo (UHU), Natalia Serrano (Qindel)
4// Description: Updates UDS with the number of available computers depending on OG's calendars and other circumstances
5// *********************************************************************
6
7include_once("./controlacceso.php");
8include_once("./includes/CreaComando.php");
9include_once("./includes/timezone.php");
10include_once("./includes/uds.php");
11include_once("./clases/AdoPhp.php");
12
13$OG_REST_URL = 'https://localhost/opengnsys/rest/';
14
15/**
16 *         uds_getHeaders ($auth_token, $scrambler)
17 * @brief  Builds set of authentication headers from a couple of UDS params
18 * @param  string  authentication token
19 * @param  string  scrambler
20 * @return array   headers
21 */
22function uds_getHeaders ($auth_token, $scrambler) {
23    $headers = [
24        'X-Auth-Token: ' . $auth_token,                  // Authentication token to access REST API of UDS -- MUST be present in all requests except login request
25        'Content-Type: ' . 'application/json',
26        'User-Agent: '   . 'UDS Test Linux Client 1.0',  // important to include "Linux" on UA to allow UDS to know OS. If not present, UDS will not know wich OS is connecting, and will not send the correct services
27        'Scrambler: '    . $scrambler,                   // This header is a cryptographic key -- MUST BE INCLUDED in all requests except login request
28    ];
29    return $headers;
30}
31
32/**
33 *         db_fetch_apikey()
34 * @brief  Retrieves API key for the first user (assumed admin) from the OG database
35 * @return string  api key
36 */
37function db_fetch_apikey() {
38    global $cnx;
39    $cmd = CreaComando ($cnx);
40    if (!$cmd) { die ('ACCESS_ERROR'); }
41
42    $cmd->texto = 'SELECT apikey FROM usuarios WHERE idusuario=1';
43    $rs = new Recordset;
44    $rs->Comando = &$cmd;
45
46    if (!$rs->Abrir()) return (null);
47
48    $rs->Primero();
49    if ($rs->EOF) { return (null); }
50
51    $k = $rs->campos['apikey'];
52    $rs->Cerrar();
53    return $k;
54}
55
56/**
57 *         db_fetchCals()
58 * @brief  Retrieves calendars from the database
59 * @return array   calendars
60 */
61function db_fetchCals() {
62    global $cnx;
63
64    $tbl = array();
65    $cmd = CreaComando ($cnx);
66    if (!$cmd) { die ('ACCESS_ERROR'); }
67
68    $cmd->texto = 'SELECT idcalendario, description, json_text FROM calendarios';
69    $rs = new Recordset;
70    $rs->Comando = &$cmd;
71
72    if (!$rs->Abrir()) return (false);
73
74    $rs->Primero();
75    if ($rs->EOF) { return ($tbl); }
76
77    $id = $rs->campos['idcalendario'];
78    $desc = $rs->campos['description'];
79    $txt = $rs->campos['json_text'];
80    $tbl[$id] = array (
81        'id'   => $id,
82        'desc' => $desc,
83        'json' => json_decode($txt),
84    );
85
86    while (1) {
87        $rs->Siguiente();
88        if ($rs->EOF) { break; }
89
90        $id = $rs->campos['idcalendario'];
91        $desc = $rs->campos['description'];
92        $txt = $rs->campos['json_text'];
93        $tbl[$id] = array (
94            'id'   => $id,
95            'desc' => $desc,
96            'json' => json_decode($txt),
97        );
98    }
99
100    $rs->Cerrar();
101    return $tbl;
102}
103
104/**
105 *         uds_login ($auth, $username, $password)
106 * @brief  Log into UDS
107 * @param  string  UDS authenticator
108 * @param  string  user
109 * @param  string  password
110 * @return object  response from the server, contains result, token, version and scrambler
111 */
112function uds_login ($auth, $username, $password) {
113    global $UDS_REST_URL;
114
115    $parameters = [
116        'auth'     => $auth,
117        'username' => $username,
118        'password' => $password
119    ];
120
121    $payload = json_encode ($parameters);
122
123    $ch = curl_init();
124    curl_setopt ($ch, CURLOPT_URL, $UDS_REST_URL."auth/login");
125    curl_setopt ($ch, CURLOPT_POST, 1);
126    curl_setopt ($ch, CURLOPT_POSTFIELDS, $payload);
127    curl_setopt ($ch, CURLOPT_HTTPHEADER, array ('Content-Type:application/json'));
128    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
129
130    // In real life you should use something like:
131    // curl_setopt ($ch, CURLOPT_POSTFIELDS, http_build_query (array ('postvar1' => 'value1')));
132
133    $server_output = json_decode (curl_exec ($ch));
134    curl_close ($ch);
135
136    return $server_output;
137}
138
139/**
140 *         uds_getServiceInfo ($headers, $providerId, $serviceId)
141 * @brief  Get service information from UDS
142 * @param  array   UDS headers
143 * @param  string  provider id
144 * @param  string  service id
145 * @return object  response from the server
146 */
147function uds_getServiceInfo ($headers, $providerId, $serviceId) {
148    global $UDS_REST_URL;
149
150    $ch = curl_init();
151    curl_setopt ($ch, CURLOPT_URL, $UDS_REST_URL."providers/".$providerId."/services/".$serviceId);
152    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
153    curl_setopt ($ch, CURLOPT_HTTPHEADER, $headers);
154
155    $server_output = json_decode (curl_exec ($ch));
156    print_r (curl_error ($ch));
157    curl_close ($ch);
158
159    return $server_output;
160}
161
162/**
163 *         uds_getAllServicePools ($headers)
164 * @brief  Get all service pools from UDS
165 * @param  array   UDS headers
166 * @return object  response from the server
167 */
168function uds_getAllServicePools ($headers) {
169    global $UDS_REST_URL;
170
171    $ch = curl_init();
172    curl_setopt ($ch, CURLOPT_URL, $UDS_REST_URL."servicespools/overview");
173    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
174    curl_setopt ($ch, CURLOPT_HTTPHEADER, $headers);
175
176    $server_output = json_decode (curl_exec ($ch));
177    curl_close ($ch);
178
179    return $server_output;
180}
181
182/**
183 *         uds_setServicePool ($headers, $servicePool)
184 * @brief  Writes service pool information to UDS
185 * @param  array   UDS headers
186 * @param  object  service pool details
187 * @return object  response from the server
188 */
189function uds_setServicePool ($headers, $servicePool) {
190    global $UDS_REST_URL;
191
192    $payload = json_encode ($servicePool);
193
194    $ch = curl_init();
195    curl_setopt ($ch, CURLOPT_URL, $UDS_REST_URL."servicespools/".$servicePool->id);
196    curl_setopt ($ch, CURLOPT_POST, 1);
197    curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "PUT");
198    curl_setopt ($ch, CURLOPT_POSTFIELDS, $payload);
199    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
200    curl_setopt ($ch, CURLOPT_HTTPHEADER, $headers);
201
202    $server_output = curl_exec ($ch);
203    curl_close ($ch);
204
205    return json_decode ($server_output);
206}
207
208/**
209 *         og_getAula ($idCentro, $idAula)
210 * @brief  Gets lab information from OG
211 * @param  int     building id
212 * @param  int     lab id
213 * @return object  response from the server
214 */
215function og_getAula ($idCentro, $idAula) {
216    global $OG_REST_URL;
217    global $OG_REST_AUTH;
218
219    $result = null;
220    $url = $OG_REST_URL."ous/".$idCentro."/labs/".$idAula;
221
222    $ch = curl_init();
223    curl_setopt ($ch, CURLOPT_URL, $url);
224    curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
225    curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
226    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
227    curl_setopt ($ch, CURLOPT_HTTPHEADER, [
228        'Accept: application/json',
229        'Authorization: '.$OG_REST_AUTH
230    ]);
231
232
233    $server_output = json_decode (curl_exec ($ch));
234    $curl_errno = curl_errno ($ch);
235    $curl_error = curl_error ($ch);
236    if ($curl_errno) {
237        printf ("error (%s) errno (%d)\n", $curl_error, $curl_errno);
238        return null;
239    }
240
241    $code = curl_getinfo ($ch, CURLINFO_RESPONSE_CODE);
242    curl_close ($ch);
243
244    if ($code <= 201) {
245        $result = $server_output;
246    }
247
248    return $result;
249}
250
251/**
252 *         og_getClientDiskConfig ($idCentro, $idAula, $idCliente)
253 * @brief  Gets information about disks of a client from OG
254 * @param  int     building id
255 * @param  int     lab id
256 * @param  int     client id
257 * @return object  response from the server
258 */
259function og_getClientDiskConfig ($idCentro, $idAula, $idCliente) {
260    global $OG_REST_URL;
261    global $OG_REST_AUTH;
262
263    $result = null;
264    $url = $OG_REST_URL."ous/".$idCentro."/labs/".$idAula."/clients/".$idCliente."/diskcfg";
265
266    $ch = curl_init();
267    curl_setopt ($ch, CURLOPT_URL, $url);
268    curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
269    curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
270    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
271    curl_setopt ($ch, CURLOPT_HTTPHEADER, [
272        'Accept: application/json',
273        'Authorization: '.$OG_REST_AUTH
274    ]);
275
276    $server_output = json_decode (curl_exec ($ch));
277    $curl_errno = curl_errno ($ch);
278    $curl_error = curl_error ($ch);
279    if ($curl_errno) {
280        printf ("error (%s) errno (%d)\n", $curl_error, $curl_errno);
281        return null;
282    }
283
284    $code = curl_getinfo ($ch, CURLINFO_RESPONSE_CODE);
285    curl_close ($ch);
286
287    if ($code <= 201) {
288        $result = $server_output;
289    }
290
291    return $result;
292}
293
294/**
295 *         og_aula_is_remote ($cal_id)
296 * @brief  Checks whether lab is remote right now
297 * @param  int     calendar id
298 * @return bool    whether lab is remote (true) or not (false)
299 */
300function og_aula_is_remote ($cal_id) {
301    global $cals, $tz;
302    $ruleset = $cals[$cal_id]['json']->remotepc_calendar->ruleset; //print_r($ruleset);
303
304    $dt = new DateTime ('now', new DateTimeZone ($tz));
305    $dow = strtolower ($dt->format ('D'));  // textual representation of a day, three letters, 'Mon' through 'Sun'
306    $hour = $dt->format ('G');              // 24-hour without leading zeros
307    $ts = $dt->format ('U');                // unix epoch
308
309    // primero recorremos todas las reglas mirando solo las que tienen remote=false (ie. presencial)
310    // si estamos fuera de todos estos rangos, es que estamos en remoto: return 1
311    // si estamos dentro de alguno de ellos, es que estamos en presencial: continuamos
312    $presencial = 0;
313    foreach ($ruleset as $r) {
314        if (array_key_exists ('remote', $r) and $r->remote) { continue; }
315        if (!array_key_exists ($dow, $r) or !$r->$dow) { continue; }
316        if ($hour < $r->from_hr or $hour > $r->to_hr) { continue; }
317        $presencial = 1; break;
318    }
319
320    if (0 == $presencial) {
321        return 1;
322    }
323
324    // si llegamos aqui, es que estamos en uno de los rangos de presencial, pero puede haber excepciones
325    // recorremos todas las reglas mirando las que tienen remote=true
326    // si estamos en alguno de esos rangos, return 1
327    foreach ($ruleset as $r) {
328        if (!array_key_exists ('remote', $r) or !$r->remote) { continue; }
329        if ($ts >= $r->from_ts and $ts <= $r->to_ts) { return 1; }
330    }
331
332    // si llegamos aqui es que estamos dentro de presencial y fuera de las excepciones: return 0
333    return 0;
334}
335// {"remotepc_calendar":{"timezone":"Europe/Madrid","ruleset":[
336//     {"remote":false,"mon":true,"tue":true,"wed":true,"thu":true,"fri":true,"from_hr":"8","to_hr":"17"},
337//     {"remote":true,"reason":"exc","from_ts":1709074800,"to_ts":1706569199}
338// ]}}
339
340function og_ordenador_cumple_criterios ($client) {
341    if ($client->status == 'oglive' || $client->status == 'linux' || $client->status == 'windows') {
342        return 1;
343    }
344
345    return 0;
346}
347
348/**
349 *         og_sondeoAula ($idCentro, $idAula, $idImagen)
350 * @brief  Gets how many clients are available for remotepc from OG
351 * @param  int     building id
352 * @param  int     lab id
353 * @param  int     image id
354 * @return int     number of clients available for remotepc
355 */
356function og_sondeoAula ($idCentro, $idAula, $idImagen) {
357    global $OG_REST_URL;
358    global $OG_REST_AUTH;
359
360    $aula = og_getAula ($idCentro, $idAula);
361    if (null === $aula || $aula->inremotepc != 1) { return 0; }
362
363    if (!og_aula_is_remote ($aula->idcalendario)) {
364        return 0;
365    }
366
367    $url = $OG_REST_URL."ous/".$idCentro."/labs/".$idAula."/clients/status";
368    $ch = curl_init();
369    curl_setopt ($ch, CURLOPT_URL, $url);
370    curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
371    curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
372    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
373    curl_setopt ($ch, CURLOPT_HTTPHEADER, [
374        'Accept: application/json',
375        'Authorization: '.$OG_REST_AUTH
376    ]);
377
378    $server_output = json_decode (curl_exec ($ch));
379    $curl_errno = curl_errno ($ch);
380    $curl_error = curl_error ($ch);
381    if ($curl_errno) {
382        printf ("error (%s) errno (%d)\n", $curl_error, $curl_errno);
383        return null;
384    }
385    $code = curl_getinfo ($ch, CURLINFO_RESPONSE_CODE);
386    curl_close ($ch);
387
388    if ($code > 201) { return 0; }
389
390    $clientsOn = 0;
391    foreach ($server_output as $client) {
392        if (!og_ordenador_cumple_criterios ($client)) { continue; }
393
394        $clientDisk = og_getClientDiskConfig ($idCentro, $idAula, $client->id);
395        if (null === $clientDisk) { continue; }
396
397        for ($p = 0; $p < count ($clientDisk->diskcfg); $p++) {
398            $part = $clientDisk->diskcfg[$p];
399            if (isset ($part->image) && $part->image->id == $idImagen) {
400                $clientsOn++;
401                break;
402            }
403        }
404    }
405
406    return $clientsOn;
407}
408
409
410
411$OG_REST_AUTH = db_fetch_apikey();
412if (null == $OG_REST_AUTH) {
413    print ("failed to fetch OG API key from the database\n");
414    exit (1);
415}
416
417$cals = db_fetchCals(); //print_r($cals);
418
419$server_output = uds_login ($UDS_AUTHENTICATOR, $UDS_USER, $UDS_PASS);
420if ($server_output->result != "ok") {
421    print_r (curl_error ($ch));
422    exit (1);
423}
424
425$headers = uds_getHeaders ($server_output->token, $server_output->scrambler);
426$servicePools = uds_getAllServicePools ($headers);
427
428foreach ($servicePools as $servicePool) {
429    $providerId = $servicePool->provider_id;
430    $serviceId = $servicePool->service_id;
431
432    $service = uds_getServiceInfo ($headers, $providerId, $serviceId);
433    if ($service === null) {
434        print ("service with providerId ($providerId) serviceId ($serviceId) is null\n");
435        continue;
436    }
437
438    // Conectar con opengnsys para ver cuantos pcs hay disponibles y enviar dicho parametro
439    $max_srvs = og_sondeoAula ($service->ou, $service->lab, $service->image);
440    if (null === $max_srvs) {
441        print ("og_sondeoAula failed\n");
442        continue;
443    }
444    $servicePool->osmanager_id = null;
445    $servicePool->max_srvs = $max_srvs;
446    $servicePool->initial_srvs = $servicePool->max_srvs;
447    $servicePool->cache_l1_srvs = 0;
448
449    $servicePool->visible = ($servicePool->max_srvs > 0);
450
451    /*
452    if ($servicePool->initial_srvs > $servicePool->max_srvs){
453        $servicePool->initial_srvs = $servicePool->max_srvs;
454    }
455    /**/
456    $sp = uds_setServicePool ($headers, $servicePool);
457    if (null === $sp) {
458        print ("uds_setServicePool failed\n");
459        continue;
460    }
461    printf ("%s: ou:%d lab:%d imagen:%d max_srvs:%d visible:%d\n", $sp->name, $service->ou, $service->lab, $service->image, $sp->max_srvs, $sp->visible);
462}
Note: See TracBrowser for help on using the repository browser.