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

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 ac933ca was fb2ee20, checked in by ramon <ramongomez@…>, 9 years ago

#708 #743: Solo activar las rutas REST de los servicios activos.

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

  • Property mode set to 100644
File size: 5.4 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['error'] = true;
45                                $response['message'] = 'Login failed. Incorrect credentials';
46                                jsonResponse(401, $response);
47                                $app->stop();
48                        }
49                } else {
50                        // Access error.
51                        $response['error'] = true;
52                        $response['message'] = "An error occurred, please try again";
53                        jsonResponse(500, $response);
54                }
55        } else {
56                // Error: missing API key.
57                $response['error'] = true;
58                $response['message'] = 'Missing Repository API key';
59                jsonResponse(400, $response);
60                $app = \Slim\Slim::getInstance();
61                $app->stop();
62        }
63}
64
65function commandExist($cmd) {
66    $returnVal = shell_exec("which $cmd");
67    return (empty($returnVal) ? false : true);
68}
69
70// Define REST routes.
71
72
73/**
74 * @brief    List all images in the repository
75 * @note     Route: /images, Method: GET
76 * @param    no
77 * @return   JSON array with imagename, file size
78 */
79$app->get('/repository/images', 'validateRepositoryApiKey',
80        function() {
81                $imgPath = '/opt/opengnsys/images';
82                $app = \Slim\Slim::getInstance();
83                // Comprobar si en la peticion se especificó un filtro por extensiones
84                $extensions = $app->request->get('extensions');
85
86                if ($manager = opendir($imgPath)) {
87                        $repoInfo=exec("df -h ".$imgPath);
88                        $repoInfo=split(" ",preg_replace('/\s+/', ' ', $repoInfo));
89
90                        $response['disk']["total"]=$repoInfo[1];
91                    $response['disk']["used"]=$repoInfo[2];
92                    $response['disk']["free"]=$repoInfo[3];
93                    $response['disk']["percent"]=$repoInfo[4];
94
95                    $response['images'] = array();
96                    while (false !== ($entry = readdir($manager))) {
97                        $include = true;
98                        if ($entry != "." && $entry != "..") {
99                                // Si se especificó algun filtro por extension, comprobamos si el fichero la cumple
100                                if($extensions){
101                                        $ext = pathinfo($imgPath."/".$entry, PATHINFO_EXTENSION);
102                                        // Puede ser una o varias dependiendo de si es array o no
103                                        if(is_array($extensions) && !in_array($ext, $extensions)){
104                                                $include = false;
105                                        }
106                                        else if(!is_array($extensions) && $extensions != $ext){
107                                                $include = false;
108                                        }
109
110                                }
111                                if($include == true){
112                                                $strFileName = $imgPath."/".$entry;
113                                                $fileInfo["file"]["name"] = $entry;
114                                                $fileInfo["file"]["size"] = filesize($strFileName);
115                                                $fileInfo["file"]["modified"] = date( "D d M Y g:i A", filemtime($strFileName));
116                                                $fileInfo["file"]["permissions"] = (is_readable($strFileName)?"r":"-").(is_writable($strFileName)?"w":"-").(is_executable($strFileName)?"x":"-");
117                                                array_push($response['images'], $fileInfo);
118                                        }
119                        }
120                    }
121                    closedir($manager);
122                    jsonResponse(200, $response);
123                }else{
124                        // Print error message.
125                        $response['error'] = true;
126                        $response['message'] = 'Images directory not found';
127                        jsonResponse(404, $response);
128                }
129                $app->stop();
130        }
131);
132
133
134/**
135 * @brief    Power on a pc or group of pcs with the MAC specified in POST parameters
136 * @note     Route: /poweron, Method: POST
137 * @param    macs      OU id.
138 * @return   JSON string ok if the power on command was sent
139 */
140$app->post('/repository/poweron', 'validateRepositoryApiKey',
141    function() {
142                $app = \Slim\Slim::getInstance();
143                // Debe venir el parametro macs en el post
144                $data = $app->request()->post();
145                if(empty($data["macs"])){
146                        // Print error message.
147                        $response['error'] = true;
148                        $response['message'] = 'Required param macs not found';
149                        jsonResponse(400, $response);
150                }
151                else{
152                        $macs = $data["macs"];
153                        $strMacs = "";
154                        foreach($macs as $mac){
155                                $strMacs .= " ".$mac;
156                        }
157                        // Ejecutar comando wakeonlan, debe estar disponible en el sistema operativo
158                        if(commandExist("wakeonlan")){
159                                $response["output"] = "Executing wakeonlan ".trim($strMacs)."\n";
160                                $response["output"] .= shell_exec("wakeonlan ".trim($strMacs));
161                                // Comprobar si el comando se ejecutórrectamente
162                        jsonResponse(200, $response);
163                        }
164                        else{
165                                // Print error message.
166                                $response['error'] = true;
167                                $response['message'] = 'Wakeonlan command not found in this repository';
168                                jsonResponse(404, $response);
169                        }
170                }
171        }
172);
173
174?>
175
176
Note: See TracBrowser for help on using the repository browser.