MCPcopy Create free account
hub / github.com/cronitorio/cronitor-cli / handlePostJob

Function handlePostJob

cmd/dash.go:2272–2380  ·  view source on GitHub ↗

handlePostJob handles POST requests to create a new job

(w http.ResponseWriter, r *http.Request)

Source from the content-addressed store, hash-verified

2270
2271// handlePostJob handles POST requests to create a new job
2272func handlePostJob(w http.ResponseWriter, r *http.Request) {
2273 if r.Method != "POST" {
2274 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
2275 return
2276 }
2277
2278 if isSafeModeEnabled {
2279 http.Error(w, "Job creation is disabled in safe mode", http.StatusForbidden)
2280 return
2281 }
2282
2283 var job Job
2284 if err := json.NewDecoder(r.Body).Decode(&job); err != nil {
2285 http.Error(w, err.Error(), http.StatusBadRequest)
2286 return
2287 }
2288
2289 // Validate required fields
2290 if job.Name == "" || job.Expression == "" || job.Command == "" || job.CrontabFilename == "" {
2291 http.Error(w, "Missing required fields", http.StatusBadRequest)
2292 return
2293 }
2294
2295 if !strings.HasPrefix(job.CrontabFilename, "user:") && job.RunAsUser == "" {
2296 http.Error(w, "Missing required field: run_as_user", http.StatusBadRequest)
2297 return
2298 }
2299
2300 // If cron.d is selected, create a new file
2301 if job.CrontabFilename == "/etc/cron.d" {
2302 // Slugify the job name for the filename
2303 filename := slugify(job.Name) + ".cron"
2304 job.CrontabFilename = filepath.Join("/etc/cron.d", filename)
2305 }
2306
2307 // Get the crontab
2308 crontab, err := lib.GetCrontab(job.CrontabFilename)
2309 if err != nil {
2310 // If the file doesn't exist, create it (for both /etc/crontab and files in /etc/cron.d)
2311 if os.IsNotExist(err) && (job.CrontabFilename == "/etc/crontab" || strings.HasPrefix(job.CrontabFilename, "/etc/cron.d")) {
2312 // Create an empty file
2313 if err := os.WriteFile(job.CrontabFilename, []byte{}, 0644); err != nil {
2314 http.Error(w, fmt.Sprintf("Failed to create crontab file: %v", err), http.StatusInternalServerError)
2315 return
2316 }
2317 crontab, err = lib.GetCrontab(job.CrontabFilename)
2318 if err != nil {
2319 http.Error(w, err.Error(), http.StatusInternalServerError)
2320 return
2321 }
2322 } else {
2323 http.Error(w, err.Error(), http.StatusInternalServerError)
2324 return
2325 }
2326 }
2327
2328 // Add the line to the crontab
2329 line := &lib.Line{

Callers 1

handleJobsFunction · 0.85

Calls 12

KeyMethod · 0.95
GetCrontabFunction · 0.92
slugifyFunction · 0.85
invalidateCrontabCacheFunction · 0.85
createDefaultNameFunction · 0.85
getCronitorApiFunction · 0.85
logFunction · 0.85
ErrorMethod · 0.80
SaveMethod · 0.80
CanonicalNameMethod · 0.80
PutMonitorsMethod · 0.80
WriteMethod · 0.45

Tested by

no test coverage detected