source: admin/WebConsole/rest/repository.php @ dee9fac

918-git-images-111dconfigfileconfigure-oglivegit-imageslgromero-new-oglivemainmaint-cronmount-efivarfsmultivmmultivm-ogboot-installerogClonningEngineogboot-installer-jenkinsoglive-ipv6test-python-scriptsticket-301ticket-50ticket-50-oldticket-577ticket-585ticket-611ticket-612ticket-693ticket-700ubu24tplunification2use-local-agent-oglivevarios-instalacionwebconsole3
Last change on this file since dee9fac was 1108dfa, checked in by ramon <ramongomez@…>, 8 years ago

#743: Ruta REST /repository/poweron de repositorio usa parámetros de entrada en formato JSON.

git-svn-id: https://opengnsys.es/svn/branches/version1.1@5171 a21b9725-9963-47de-94b9-378ad31fedc9

  • Property mode set to 100644
File size: 5.2 KB
Line 
1<?php
2/**
3 * @file    repository.php
4 * @brief   OpenGnsys Repository REST API manager.
5 * @warning All input and output messages are formatted in JSON.
6 * @note    Some ideas are based on article "How to create REST API for Android app using PHP, Slim and MySQL" by Ravi Tamada, thanx.
7 * @license GNU GPLv3+
8 * @author  Juan Manuel Bardallo SIC Universidad de Huelva
9 * @version 1.0
10 * @date    2016-04-06
11 */
12
13// Auxiliar functions.
14/**
15 * @brief    Validate API key included in "Authorization" HTTP header.
16 * @return   JSON response on error.
17 */
18function validateRepositoryApiKey() {
19        $response = array();
20
21        // Read Authorization HTTP header.
22        $headers = apache_request_headers();
23        if (! empty($headers['Authorization'])) {
24                // Assign user id. that match this key to global variable.
25                $apikey = htmlspecialchars($headers['Authorization']);
26                // El repositorio recupera el token desde el fichero de configuracion ogAdmRepo.cfg
27                $confFile = fopen("../../etc/ogAdmRepo.cfg", "r");
28
29                // Leemos cada linea hasta encontrar la clave "ApiToken"
30                if ($confFile) {
31                        $found = false;
32                        while(!feof($confFile)){
33                                $line = fgets($confFile);
34                                $key = strtok($line,"=");
35                                if($key == "ApiToken"){
36                                        $token = trim(strtok("="));
37                                        if(strcmp($apikey,$token) == 0){
38                                                $found = true;
39                                        }
40                                }
41                        }
42                        if (!$found){
43                                // Credentials error.
44                                $response['message'] = 'Login failed. Incorrect credentials';
45                                jsonResponse(401, $response);
46                                $app->stop();
47                        }
48                } else {
49                        // Access error.
50                        $response['message'] = "An error occurred, please try again";
51                        jsonResponse(500, $response);
52                }
53        } else {
54                // Error: missing API key.
55                $response['message'] = 'Missing Repository API key';
56                jsonResponse(400, $response);
57                $app = \Slim\Slim::getInstance();
58                $app->stop();
59        }
60}
61
62function commandExist($cmd) {
63    $returnVal = shell_exec("which $cmd");
64    return (empty($returnVal) ? false : true);
65}
66
67// Define REST routes.
68
69
70/**
71 * @brief    List all images in the repository
72 * @note     Route: /images, Method: GET
73 * @param    no
74 * @return   JSON array with imagename, file size
75 */
76$app->get('/repository/images', 'validateRepositoryApiKey',
77        function() {
78                $imgPath = '/opt/opengnsys/images';
79                $app = \Slim\Slim::getInstance();
80                // Comprobar si en la peticion se especificó un filtro por extensiones
81                $extensions = $app->request->get('extensions');
82
83                if ($manager = opendir($imgPath)) {
84                        $repoInfo=exec("df -h ".$imgPath);
85                        $repoInfo=split(" ",preg_replace('/\s+/', ' ', $repoInfo));
86
87                        $response['disk']["total"]=$repoInfo[1];
88                    $response['disk']["used"]=$repoInfo[2];
89                    $response['disk']["free"]=$repoInfo[3];
90                    $response['disk']["percent"]=$repoInfo[4];
91
92                    $response['images'] = array();
93                    while (false !== ($entry = readdir($manager))) {
94                        $include = true;
95                        if ($entry != "." && $entry != "..") {
96                                // Si se especificó algun filtro por extension, comprobamos si el fichero la cumple
97                                if($extensions){
98                                        $ext = pathinfo($imgPath."/".$entry, PATHINFO_EXTENSION);
99                                        // Puede ser una o varias dependiendo de si es array o no
100                                        if(is_array($extensions) && !in_array($ext, $extensions)){
101                                                $include = false;
102                                        }
103                                        else if(!is_array($extensions) && $extensions != $ext){
104                                                $include = false;
105                                        }
106
107                                }
108                                if($include == true){
109                                                $strFileName = $imgPath."/".$entry;
110                                                $fileInfo["file"]["name"] = $entry;
111                                                $fileInfo["file"]["size"] = filesize($strFileName);
112                                                $fileInfo["file"]["modified"] = date( "D d M Y g:i A", filemtime($strFileName));
113                                                $fileInfo["file"]["permissions"] = (is_readable($strFileName)?"r":"-").(is_writable($strFileName)?"w":"-").(is_executable($strFileName)?"x":"-");
114                                                array_push($response['images'], $fileInfo);
115                                        }
116                        }
117                    }
118                    closedir($manager);
119                    jsonResponse(200, $response);
120                }else{
121                        // Print error message.
122                        $response['message'] = 'Images directory not found';
123                        jsonResponse(404, $response);
124                }
125                $app->stop();
126        }
127);
128
129
130/**
131 * @brief    Power on a pc or group of pcs with the MAC specified in POST parameters
132 * @note     Route: /poweron, Method: POST
133 * @param    macs      OU id.
134 * @return   JSON string ok if the power on command was sent
135 */
136$app->post('/repository/poweron', 'validateRepositoryApiKey',
137    function() {
138                $app = \Slim\Slim::getInstance();
139                // Debe venir el parametro macs en el post (objeto JSON con array de MACs)
140                $data = $app->request()->post();
141                if(empty($data->macs)){
142                        // Print error message.
143                        $response['message'] = 'Required param macs not found';
144                        jsonResponse(400, $response);
145                }
146                else{
147                        $macs = $data->macs;
148                        $strMacs = "";
149                        foreach($macs as $mac){
150                                $strMacs .= " ".$mac;
151                        }
152                        // Ejecutar comando wakeonlan, debe estar disponible en el sistema operativo
153                        if(commandExist("wakeonlan")){
154                                $response["output"] = "Executing wakeonlan ".trim($strMacs)."\n";
155                                $response["output"] .= shell_exec("wakeonlan ".trim($strMacs));
156                                // Comprobar si el comando se ejecutórrectamente
157                        jsonResponse(200, $response);
158                        }
159                        else{
160                                // Print error message.
161                                $response['message'] = 'Wakeonlan command not found in this repository';
162                                jsonResponse(404, $response);
163                        }
164                }
165        }
166);
167
168?>
Note: See TracBrowser for help on using the repository browser.