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

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 df7fd0b was a38cb26, checked in by ramon <ramongomez@…>, 8 years ago

#708: Guardar datos de fin de sessión remota y comandos de aviso.

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

  • Property mode set to 100644
File size: 7.3 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        $app = \Slim\Slim::getInstance();
21
22        // Read Authorization HTTP header.
23        $headers = apache_request_headers();
24        if (! empty($headers['Authorization'])) {
25                // Assign user id. that match this key to global variable.
26                $apikey = htmlspecialchars($headers['Authorization']);
27                // El repositorio recupera el token desde el fichero de configuracion ogAdmRepo.cfg
28                $confFile = fopen("../../etc/ogAdmRepo.cfg", "r");
29
30                // Leemos cada linea hasta encontrar la clave "ApiToken"
31                if ($confFile) {
32                        $found = false;
33                        while(!feof($confFile)){
34                                $line = fgets($confFile);
35                                $key = strtok($line,"=");
36                                if($key == "ApiToken"){
37                                        $token = trim(strtok("="));
38                                        if(strcmp($apikey,$token) == 0){
39                                                $found = true;
40                                        }
41                                }
42                        }
43                        if (!$found){
44                                // Credentials error.
45                                $response['message'] = 'Login failed. Incorrect credentials';
46                                jsonResponse(401, $response);
47                                $app->stop();
48                        }
49                } else {
50                        // Cannot access configuration file.
51                        $response['message'] = "An error occurred, please try again";
52                        jsonResponse(500, $response);
53                }
54        } else {
55                // Error: missing API key.
56                $response['message'] = 'Missing Repository API key';
57                jsonResponse(400, $response);
58        }
59}
60
61function commandExist($cmd) {
62    $returnVal = shell_exec("which $cmd");
63    return (empty($returnVal) ? false : true);
64}
65
66
67// Define REST routes.
68
69
70/**
71 * @brief    List all images in the repository
72 * @note     Route: /repository/images, Method: GET
73 * @param    no
74 * @return   JSON object with directory, images array, ous array and disk data.
75 */
76$app->get('/repository/images(/)', 'validateRepositoryApiKey',
77    function() use ($app) {
78        $response = array();
79        // Read repository information file.
80        $cfgFile = '/opt/opengnsys/etc/repoinfo.json';
81        $response = json_decode(@file_get_contents($cfgFile), true);
82        // Check if directory exists.
83        $imgPath = @$response['directory'];
84        if (is_dir($imgPath)) {
85                // Complete global image information.
86                for ($i=0; $i<sizeof(@$response['images']); $i++) {
87                        $img = $response['images'][$i];
88                        $file = $imgPath."/".($img['type']==="dir" ? $img["name"] : $img["name"].".".$img["type"]);
89                        $response['images'][$i]['size'] = @stat($file)['size'];
90                        $response['images'][$i]['modified'] = date("Y-m-d H:i:s", @stat($file)['mtime']);
91                        $response['images'][$i]['mode'] = substr(decoct(@stat($file)['mode']), -4);
92                        $backupfile = "$file.ant";
93                        if (file_exists($backupfile)) {
94                                $response['images'][$i]['backedup'] = true;
95                                $response['images'][$i]['backupsize'] = @stat($backupfile)['size'];
96                        } else {
97                                $response['images'][$i]['backedup'] = false;
98                        }
99                        $lockfile = "$file.lock";
100                        $response['images'][$i]['locked'] = file_exists($lockfile);
101                }
102                // Complete image in OUs information.
103                for ($j=0; $j<sizeof(@$response['ous']); $j++) {
104                        for ($i=0; $i<sizeof(@$response['ous'][$j]['images']); $i++) {
105                                $img = $response['ous'][$j]['images'][$i];
106                                $file = $imgPath."/".$response['ous'][$j]['subdir']."/".($img['type']==="dir" ? $img["name"] : $img["name"].".".$img["type"]);
107                                $response['ous'][$j]['images'][$i]['size'] = @stat($file)['size'];
108                                $response['ous'][$j]['images'][$i]['modified'] = date("Y-m-d H:i:s", @stat($file)['mtime']);
109                                $response['ous'][$j]['images'][$i]['mode'] = substr(decoct(@stat($file)['mode']), -4);
110                                $response['ous'][$j]['images'][$i]['backedup'] = false;
111                                $lockfile = "$file.lock";
112                                $response['ous'][$j]['images'][$i]['locked'] = file_exists($lockfile);
113                        }
114                }
115                // Retrieve disk information.
116                $total = disk_total_space($imgPath);
117                $free = disk_free_space($imgPath);
118                $response['disk']['total'] = $total;
119                $response['disk']['free'] = $free;
120                // JSON response.
121                jsonResponse(200, $response);
122        } else {
123                // Print error message.
124                $response['message'] = 'Images directory not found';
125                jsonResponse(404, $response);
126        }
127        $app->stop();
128    }
129);
130
131
132/**
133 * @brief    List image data
134 * @note     Route: /repository/image/:imagename, Method: GET
135 * @param    no
136 * @return   JSON object with image data.
137 */
138$app->get('/repository/image(/:ouname)/:imagename(/)', 'validateRepositoryApiKey',
139    function($ouname="/", $imagename) use ($app) {
140        $images = array();
141        $response = array();
142        // Search image name in repository information file.
143        $cfgFile = '/opt/opengnsys/etc/repoinfo.json';
144        $json = json_decode(@file_get_contents($cfgFile), true);
145        $imgPath = @$json['directory'];
146        if (empty($ouname) or $ouname == "/") {
147                // Search in global directory.
148                $images = @$json['images'];
149        } else {
150                // Search in OU directory.
151                for ($i=0; $i<sizeof(@$json['ous']); $i++) {
152                        if ($json['ous'][$i]['subdir'] == $ouname) {
153                                $images = $json['ous'][$i]['images'];
154                        }
155                }
156        }
157        // Search image.
158        foreach ($images as $img) {
159                if ($img['name'] == $imagename) {
160                        $response = $img;
161                        $file = "$imgPath/$ouname/" . ($img['type']==="dir" ? $img["name"] : $img["name"].".".$img["type"]);
162                        $response['size'] = @stat($file)['size'];
163                        $response['modified'] = date("Y-m-d H:i:s", @stat($file)['mtime']);
164                        $response['mode'] = substr(decoct(@stat($file)['mode']), -4);
165                        $backupfile = "$file.ant";
166                        if (file_exists($backupfile)) {
167                                $response['backedup'] = true;
168                                $response['backupsize'] = @stat($backupfile)['size'];
169                        } else {
170                                $response['backedup'] = false;
171                        }
172                        $lockfile = "$file.lock";
173                        $response['locked'] = file_exists($lockfile);
174                }
175        }
176        if (isset ($response)) {
177                // JSON response.
178                jsonResponse(200, $response);
179        } else {
180                // Print error message.
181                $response['message'] = 'Image not found';
182                jsonResponse(404, $response);
183        }
184        $app->stop();
185    }
186);
187
188
189/**
190 * @brief    Power on a pc or group of pcs with the MAC specified in POST parameters
191 * @note     Route: /poweron, Method: POST
192 * @param    macs      OU id.
193 * @return   JSON string ok if the power on command was sent
194 */
195$app->post('/repository/poweron', 'validateRepositoryApiKey',
196    function() {
197                $app = \Slim\Slim::getInstance();
198                // Debe venir el parametro macs en el post (objeto JSON con array de MACs)
199                $data = $app->request()->post();
200                if(empty($data->macs)){
201                        // Print error message.
202                        $response['message'] = 'Required param macs not found';
203                        jsonResponse(400, $response);
204                }
205                else{
206                        $macs = $data->macs;
207                        $strMacs = "";
208                        foreach($macs as $mac){
209                                $strMacs .= " ".$mac;
210                        }
211                        // Ejecutar comando wakeonlan, debe estar disponible en el sistema operativo
212                        if(commandExist("wakeonlan")){
213                                $response["output"] = "Executing wakeonlan ".trim($strMacs)."\n";
214                                $response["output"] .= shell_exec("wakeonlan ".trim($strMacs));
215                                // Comprobar si el comando se ejecutórrectamente
216                        jsonResponse(200, $response);
217                        }
218                        else{
219                                // Print error message.
220                                $response['message'] = 'Wakeonlan command not found in this repository';
221                                jsonResponse(404, $response);
222                        }
223                }
224        }
225);
226
227?>
Note: See TracBrowser for help on using the repository browser.