Merge branch 'master' of https://github.com/szmoore/MCTX3420
[matches/MCTX3420.git] / server / control.c
1 /**
2  * @file control.c
3  * @brief Handles all client control requests (admin related)
4  */
5 #include "common.h"
6 #include "options.h"
7 #include "control.h"
8 #include "sensor.h"
9 #include "actuator.h"
10 #include <dirent.h>
11
12 typedef struct ControlData {
13         ControlModes current_mode;
14         pthread_mutex_t mutex;
15         struct timeval start_time;
16         char user_name[31]; // The user who owns the currently running experiment
17 } ControlData;
18
19 ControlData g_controls = {CONTROL_STOP, PTHREAD_MUTEX_INITIALIZER, {0}};
20
21 bool PathExists(const char *path) 
22 {
23         FILE *fp = fopen(path, "r");
24         if (fp) {
25                 fclose(fp);
26                 return true;
27         }
28         return false;
29 }
30
31 /**
32  * System control handler. This covers high-level control, including
33  * admin related functions and starting/stopping experiments..
34  * @param context The context to work in
35  * @param params The input parameters
36  */
37 void Control_Handler(FCGIContext *context, char *params) {
38         const char *action = "";
39         const char *name = "";
40         bool force = false;
41         ControlModes desired_mode;
42         
43         
44         
45
46
47         // Login/auth now handled entirely in fastcgi.c and login.c
48         //TODO: Need to not have the ability for any user to stop someone else' experiment...
49         // (achieve by storing the username of the person running the current experiment, even when they log out?)
50         // (Our program should only realisitically support a single experiment at a time, so that should be sufficient)
51         FCGIValue values[3] = {
52                 {"action", &action, FCGI_REQUIRED(FCGI_STRING_T)},
53                 {"force", &force, FCGI_BOOL_T},
54                 {"name", &name, FCGI_STRING_T}
55         };
56
57
58         if (!FCGI_ParseRequest(context, params, values, 3))
59                 return;
60
61         //HACKETY HACK HACK (should really be a seperate function)
62         if (strcmp(action, "list") == 0)
63         {
64                 DIR * dir = opendir(context->user_name);
65                 if (dir == NULL)
66                 {
67                         FCGI_RejectJSON(context, "Failed to open user directory");
68                         return;
69                 }
70                 struct dirent * ent;
71                 FCGI_BeginJSON(context, STATUS_OK);
72                 FCGI_JSONKey("experiments");
73                 FCGI_PrintRaw("[");
74
75                 bool first = true;
76                 while ((ent = readdir(dir)) != NULL)
77                 {
78                         char * c;
79                         for (c = ent->d_name; *c != '\0' && *c != '.'; ++c);
80
81                         if (*c != '\0' && strcmp(c, ".exp") == 0)
82                         {
83                                 if (!first)
84                                         FCGI_PrintRaw(",");
85                                 *c = '\0'; // Ummm... probably not a great idea
86                                 FCGI_PrintRaw(ent->d_name);
87                                 first = false;
88                         }
89                 }
90                 FCGI_PrintRaw("]");
91                 FCGI_EndJSON();
92                 
93                 return; // Dear god this is terrible
94         }
95         //TODO: Need a "load" action to set data files (but not run) from a past experiment
96
97         //TODO: Need a "delete" action so that people can overwrite experiments (without all this "force" shenanigans)
98         
99         if (!strcmp(action, "emergency")) {
100                 desired_mode = CONTROL_EMERGENCY;
101         } else if (!strcmp(action, "start")) {
102                 desired_mode = CONTROL_START;
103         } else if (!strcmp(action, "pause")) {
104                 desired_mode = CONTROL_PAUSE;
105         } else if (!strcmp(action, "resume")) {
106                 desired_mode = CONTROL_RESUME;
107         } else if (!strcmp(action, "stop")) {
108                 desired_mode = CONTROL_STOP; 
109         } else {
110                 FCGI_RejectJSON(context, "Unknown action specified.");
111                 return;
112         }
113
114         if (*g_controls.user_name != '\0' && strcmp(g_controls.user_name,context->user_name) != 0)
115         {
116                 if (context->user_type != USER_ADMIN)
117                 {
118                         FCGI_RejectJSON(context, "Another user has an experiment in progress.");
119                         return;
120                 }
121                 
122                 if (!force)
123                 {
124                         Log(LOGERR, "User %s is currently running an experiment!", g_controls.user_name);
125                         FCGI_RejectJSON(context, "Pass \"force\" to take control over another user's experiment");
126                         return;
127                 }
128         }
129
130         
131         
132         //HACK
133         chdir(context->user_name);
134
135         void *arg = NULL;
136         if (desired_mode == CONTROL_START) {
137                 if (PathExists(name) && !force) {
138                         FCGI_RejectJSON(context, "An experiment with that name already exists.");
139                         chdir(g_options.root_dir); // REVERSE HACK
140                         return;
141                 }
142                 char * c = (char*)name;
143                 for (c = (char*)name; *c != '\0' && *c != '.'; ++c);
144                 if (*c == '.')
145                 {
146                         FCGI_RejectJSON(context, "Can't include '.' characters in experiment names (at this point we don't care anymore, go find someone who does).");
147                         chdir(g_options.root_dir); // REVERSE HACK
148                         return;
149                 }
150                 arg = (void*)name;
151         }
152
153         
154
155         const char *ret;
156         if ((ret = Control_SetMode(desired_mode, arg)) != NULL) 
157         {
158                 FCGI_RejectJSON(context, ret);
159         } 
160         else 
161         {
162                 if (desired_mode == CONTROL_STOP)
163                         g_controls.user_name[0] = '\0';
164                 else
165                 {
166                         snprintf(g_controls.user_name, sizeof(g_controls.user_name), context->user_name);
167                 }
168                 FCGI_BeginJSON(context, STATUS_OK);
169                 FCGI_JSONPair("description", "ok");
170                 FCGI_EndJSON();
171         }
172
173         //REVERSE HACK
174         chdir(g_options.root_dir);
175 }
176
177 /**
178  * Sets the mode to the desired mode, if possible.
179  * @param desired_mode The mode to be set to
180  * @param arg An argument specific to the mode to be set. 
181  * @return NULL on success, an error message on failure.
182  */
183 const char* Control_SetMode(ControlModes desired_mode, void * arg)
184 {
185         const char *ret = NULL;
186
187         pthread_mutex_lock(&(g_controls.mutex));
188         if (g_controls.current_mode == desired_mode)
189                 ret = "Already in the desired mode.";
190         else if (g_controls.current_mode == CONTROL_EMERGENCY && desired_mode != CONTROL_STOP)
191                 ret = "In emergency mode. You must stop before continuing.";
192         else switch (desired_mode) {
193                 case CONTROL_START:
194                         if (g_controls.current_mode == CONTROL_STOP) {
195                                 const char * name = arg;
196                                 if (!*name)
197                                         ret = "An experiment name must be specified";
198                                 else if (strpbrk(name, INVALID_CHARACTERS))
199                                         ret = "The experiment name must not contain: " INVALID_CHARACTERS_JSON;
200                                 else {
201                                         FILE *fp = fopen((const char*) arg, "a");
202                                         if (fp) {
203                                                 fclose(fp);
204                                                 gettimeofday(&(g_controls.start_time), NULL);
205                                         } else
206                                                 ret = "Cannot open experiment name marker";
207                                 }
208                         } else 
209                                 ret = "Cannot start when not in a stopped state.";
210                 break;
211                 case CONTROL_PAUSE:
212                         if (g_controls.current_mode != CONTROL_START)
213                                 ret = "Cannot pause when not in a running state.";
214                 break;
215                 case CONTROL_RESUME:
216                         if (g_controls.current_mode != CONTROL_PAUSE)
217                                 ret = "Cannot resume when not in a paused state.";
218                 break;
219                 case CONTROL_EMERGENCY:
220                         if (g_controls.current_mode != CONTROL_START) //pfft
221                                 ret = "Not running so how can there be an emergency?";
222                 break;
223                 default:
224                 break;
225         }
226         
227         if (ret == NULL) {
228                 Actuator_SetModeAll(desired_mode, arg);
229                 Sensor_SetModeAll(desired_mode, arg);
230                 if (desired_mode != CONTROL_RESUME)
231                         g_controls.current_mode = desired_mode;
232                 else
233                         g_controls.current_mode = CONTROL_START;
234         }
235         pthread_mutex_unlock(&(g_controls.mutex));
236         return ret;
237 }
238
239 /**
240  * Gets a string representation of the current mode
241  * @param mode The mode to get a string representation of
242  * @return The string representation of the mode
243  */
244 const char * Control_GetModeName() {
245         const char * ret = "Unknown";
246
247         switch (g_controls.current_mode) {
248                 case CONTROL_START: ret = "Running"; break;
249                 case CONTROL_PAUSE: ret = "Paused"; break;
250                 case CONTROL_RESUME: ret = "Resumed"; break;
251                 case CONTROL_STOP: ret = "Stopped"; break;
252                 case CONTROL_EMERGENCY: ret = "Emergency mode"; break;
253         }
254         return ret;
255 }
256
257 /**
258  * Gets the start time for the current experiment
259  * @return the start time
260  */
261 const struct timeval* Control_GetStartTime() {
262         return &g_controls.start_time;
263 }

UCC git Repository :: git.ucc.asn.au