source: admin/WebConsole/rest/repository.php @ 4d92ee0d

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-instalacion
Last change on this file since 4d92ee0d was e57b608, checked in by Ramón M. Gómez <ramongomez@…>, 6 years ago

#891: Boot (wake) command is sent by both server and client repository.

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