예제 #1
0
func Deploy(w http.ResponseWriter, r *http.Request) {

	conn, err := amqp.Dial("amqp://localhost://")
	if err != nil {
		panic(err)
	}

	defer conn.Close()

	ch, err := conn.Channel()
	if err != nil {
		panic(err)
	}

	var args []string
	args = append(args, "deploy.yml")

	task, err := celery.NewTask("tasks.run_playbook", args, nil)
	if err != nil {
		panic(err)
	}

	err = task.Publish(ch, "", "celery")

	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.WriteHeader(http.StatusAccepted)
	if err := json.NewEncoder(w).Encode(jsonResponse{Code: http.StatusAccepted, Message: "Request to deploy via Ansible has been accepted"}); err != nil {
		panic(err)
	}

}
// POST http://go:8080/tasks
// {"Name":"<taskName", "Args": [<task params>]}
// E.G. {"Name": "tasks.add", "Args": ["4", "8"]}
func (t *Tasks) PostTask(w rest.ResponseWriter, r *rest.Request) {
	log.Printf("postTask - Received a task.")
	task := Task{}
	err := r.DecodeJsonPayload(&task)
	if err != nil {
		log.Printf("postTask - error reading payload.")
		rest.Error(w, err.Error(), http.StatusInternalServerError)
	} else {
		log.Printf("postTask - '%s'", task.Name)
		// we have a payload, create the celery task
		celeryTask, err := celery.NewTask(task.Name, task.Args, task.Kwargs)
		if err != nil {
			log.Printf("Could not create celery task: %+v \n", err)
			rest.Error(w, "Failed to create the celery task requested.", http.StatusBadRequest)
		} else {
			//we have created a task, now open a channel
			ch, err := t.Connection.Channel()
			if err != nil {
				log.Printf("Could not open channel: %+v \n", err)
				rest.Error(w, "Error connecting to celery", http.StatusInternalServerError)
			} else {
				//we have a channel so publish the task
				defer ch.Close()
				err = celeryTask.Publish(ch, "", "celery")
				if err != nil {
					log.Printf("Could not publish celery task: %+v \n", err)
					rest.Error(w, "Error publishing task to celery", http.StatusInternalServerError)
				} else {
					// Success!
					result := TaskResult{"success"}
					w.WriteJson(&result)
				}
			}
		}
	}
}