+ } else {
+ FCGI_RejectJSONEx(context, STATUS_UNAUTHORIZED,
+ "Invalid control key specified.");
+ return;
+ }
+
+ void *arg = NULL;
+ if (desired_mode == CONTROL_START) {
+ if (PathExists(name) && !force) {
+ FCGI_RejectJSON(context, "An experiment with that name already exists.");
+ return;
+ }
+
+ arg = (void*)name;
+ }
+
+ const char *ret;
+ if ((ret = Control_SetMode(desired_mode, arg)) != NULL) {
+ FCGI_RejectJSON(context, ret);
+ } else {
+ FCGI_BeginJSON(context, STATUS_OK);
+ FCGI_JSONPair("description", "ok");
+ FCGI_EndJSON();
+ }
+}
+
+/**
+ * Sets the mode to the desired mode, if possible.
+ * @param desired_mode The mode to be set to
+ * @param arg An argument specific to the mode to be set.
+ * @return NULL on success, an error message on failure.
+ */
+const char* Control_SetMode(ControlModes desired_mode, void * arg)
+{
+ const char *ret = NULL;
+
+ pthread_mutex_lock(&(g_controls.mutex));
+ if (g_controls.current_mode == desired_mode)
+ ret = "Already in the desired mode.";
+ else if (g_controls.current_mode == CONTROL_EMERGENCY && desired_mode != CONTROL_STOP)
+ ret = "In emergency mode. You must stop before continuing.";
+ else switch (desired_mode) {
+ case CONTROL_START:
+ if (g_controls.current_mode == CONTROL_STOP) {
+ const char * name = arg;
+ if (!*name)
+ ret = "An experiment name must be specified";
+ else if (strpbrk(name, INVALID_CHARACTERS))
+ ret = "The experiment name must not contain: " INVALID_CHARACTERS_JSON;
+ else {
+ FILE *fp = fopen((const char*) arg, "a");
+ if (fp) {
+ fclose(fp);
+ gettimeofday(&(g_controls.start_time), NULL);
+ } else
+ ret = "Cannot open experiment name marker";
+ }
+ } else
+ ret = "Cannot start when not in a stopped state.";
+ break;
+ case CONTROL_PAUSE:
+ if (g_controls.current_mode != CONTROL_START)
+ ret = "Cannot pause when not in a running state.";
+ break;
+ case CONTROL_RESUME:
+ if (g_controls.current_mode != CONTROL_PAUSE)
+ ret = "Cannot resume when not in a paused state.";
+ break;
+ case CONTROL_EMERGENCY:
+ if (g_controls.current_mode != CONTROL_START) //pfft
+ ret = "Not running so how can there be an emergency.";
+ break;
+ default:
+ break;