func createHandler(connection *dbus.Conn) func(http.ResponseWriter, *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		r.ParseForm()
		key := r.PostForm.Get("key")
		action := r.PostForm.Get("action")
		http_status := http.StatusOK
		if unit_actions, action_exists := ConfigData[key+"-"+action]; action_exists {
			for _, unit_action := range unit_actions {
				result_channel := make(chan string, 1)
				var err error
				var result string
				switch unit_action.Action {
				case "restart", "start":
					_, err = connection.RestartUnit(unit_action.Unit, "fail", result_channel)
				case "stop":
					_, err = connection.StopUnit(unit_action.Unit, "fail", result_channel)
				}
				if err == nil {
					result = <-result_channel
				} else {
					fmt.Printf("Systemd Unit ERROR: %s", err.Error())
					w.Write([]byte(err.Error()))
					http_status = http.StatusInternalServerError
				}
				if result != "done" {
					fmt.Printf("Unexpected API result: %s", result)
					w.Write([]byte(result))
					http_status = http.StatusInternalServerError
				}
			}
		} else {
			http_status = http.StatusNotFound
			fmt.Printf("NO ACTION WAS GIVEN.")
			w.Write([]byte("NO ACTION WAS GIVEN."))
		}
		w.WriteHeader(http_status)
	}
}
Exemplo n.º 2
0
// watchSystemdService() attempts to determine the main PID of a service and
// builds a WatchedProc{} which is then sent to linuxProcMonitor()
func watchSystemdServiceProc(md *opentsdb.MultiDataPoint, conn *dbus.Conn, unit dbus.UnitStatus) error {
	// ExecMainPID can be non-running. MainPID is the pid of the running service.
	mainPIDProp, err := conn.GetUnitTypeProperty(unit.Name, "Service", "MainPID")
	if err != nil {
		return err
	}

	mainPID := mainPIDProp.Value.Value().(uint32)
	// MainPID is 0 if there is no running service.
	if mainPID == 0 {
		return nil
	}

	cmdline, err := getLinuxCmdline(fmt.Sprint(mainPID))
	if err != nil {
		return err
	}
	if cmdline == nil {
		return nil
	}

	wp := WatchedProc{
		Command:   regexp.MustCompile("^" + regexp.QuoteMeta(cmdline[0]) + "$"),
		Name:      strings.TrimSuffix(unit.Name, ".service"),
		Processes: make(map[string]int),
		ArgMatch:  regexp.MustCompile(""),
		idPool:    new(idPool)}

	// Since we only have one PID per service (at the moment), this is always set to 1
	wp.Processes[fmt.Sprint(mainPID)] = wp.get()

	if e := linuxProcMonitor(&wp, md); e != nil {
		return e
	}

	return err
}