Ejemplo n.º 1
0
func ServerActionsHandler(w http.ResponseWriter, r *auth.AuthenticatedRequest) {
	r.ParseForm()
	clientToken, ok := r.PostForm["token"]

	if ok == false {
		fmt.Fprint(w, "{\"error\": \"token wasn't specified\"}")
		return
	}

	if clientToken[0] != serverToken {
		fmt.Fprint(w, "{\"error\": \"wrong token\"}")
		return
	}

	clientAction, ok := r.PostForm["action"]

	if ok == false {
		fmt.Fprint(w, "{\"error\": \"action wasn't specified\"}")
		return
	}

	params := make(map[string]string)
	params["char_id"] = r.PostFormValue("params[char_id]")
	log.Println(params)
	processClientAction(clientAction[0], w, params)
}
Ejemplo n.º 2
0
// 编辑任务
func editTask(w http.ResponseWriter, r *auth.AuthenticatedRequest) {
	success := "true"
	msg := "更新成功!"

	servers := r.FormValue("servers")
	backupServers := r.FormValue("backup_servers")
	comment := r.FormValue("comment")
	logornot := r.FormValue("logornot")
	id := r.FormValue("id")
	now := time.Now().Format("2006-01-02 15:04:05")
	logOrNot, _ := strconv.Atoi(logornot)
	taskId, _ := strconv.Atoi(id)
	err := db.UpdateTaskInfo(servers, backupServers, comment, logOrNot, now, taskId)
	if err != nil {
		logger.Println(err)
		success = "false"
		msg = "数据存储操作出现问题!"
	}
	result := statusResult{
		Success: success,
		Msg:     msg,
	}
	rt, err := json.Marshal(result)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Fprintf(w, string(rt))
	return
}
Ejemplo n.º 3
0
func ServerStatusHandler(w http.ResponseWriter, r *auth.AuthenticatedRequest) {
	r.ParseForm()

	clientToken, ok := r.PostForm["token"]

	if ok == false {
		fmt.Fprint(w, "{\"error\": \"token wasn't specified\"}")
		return
	}

	if clientToken[0] != serverToken {
		fmt.Fprint(w, "{\"error\": \"wrong token\"}")
		return
	}

	clientTopicVersion, ok := r.PostForm["topic_version"]
	clientTopicVersionInt, err := strconv.Atoi(clientTopicVersion[0])

	if err != nil {
		clientTopicVersionInt = 0
	}

	if ok && clientTopicVersionInt != topicVersion {
		response := getStatusResponse(true)
		fmt.Fprint(w, response)
		return
	}

	timeout := make(chan bool)
	responseChan := make(chan string)
	pollIndex := len(statusPolls)
	statusPolls[pollIndex] = responseChan

	go func() {
		time.Sleep(time.Second * 35)
		timeout <- true
	}()

	select {
	case responseBody := <-responseChan:
		fmt.Fprint(w, responseBody)
		return
	case <-timeout:
		delete(statusPolls, pollIndex)
		w.WriteHeader(503)
		return
	}
}
Ejemplo n.º 4
0
// 应用新HAProxy配置文件
func applyConf(w http.ResponseWriter, r *auth.AuthenticatedRequest) {
	success := "true"
	msg := "成功应用!"

	target := r.FormValue("target")
	rebuildHAProxyConf()
	if target == "master" {
		bytes, err := ioutil.ReadFile(appConf.NewHAProxyConfPath)
		masterConf, err := os.OpenFile(appConf.MasterConf, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0666)
		defer masterConf.Close()
		masterConf.Write(bytes)
		cmd := appConf.MasterRestartScript
		cmdToRun := exec.Command(cmd)
		err = cmdToRun.Run()
		if err != nil {
			logger.Println(err)
			success = "false"
			msg = fmt.Sprintf("应用失败!%s", err.Error())
		}
	} else {
		var err error
		if appConf.CopyMethod == 1 {
			err = sshoperation.ScpHaproxyConf(appConf)
		}
		if appConf.CopyMethod == 2 {
			err = sshoperation.ConfidentialScpHAProxyConf(appConf)
		}
		if err != nil {
			success = "false"
			msg = fmt.Sprintf("应用失败!%s", err.Error())
		}
	}
	result := statusResult{
		Success: success,
		Msg:     msg,
	}
	rt, err := json.Marshal(result)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Fprintf(w, string(rt))
	return
}
Ejemplo n.º 5
0
// 删除任务
func delListenTask(w http.ResponseWriter, r *auth.AuthenticatedRequest) {
	success := "true"
	msg := "已成功删除"

	taskId := r.FormValue("taskid")
	id, _ := strconv.Atoi(taskId)
	result, err := db.DeleteTask(id)
	if err != nil {
		logger.Fatalln(err)
		success = "false"
		msg = "删除数据出错!"
	}
	rowsAffected, err := result.RowsAffected()
	if rowsAffected != 1 {
		success = "false"
		msg = fmt.Sprintf("数据删除有问题,删除了%d条", rowsAffected)
	}
	rt, _ := json.Marshal(statusResult{Success: success, Msg: msg})
	fmt.Fprintf(w, string(rt))
	return
}
Ejemplo n.º 6
0
// 申请虚拟ip端口请求处理函数
func applyVPort(w http.ResponseWriter, r *auth.AuthenticatedRequest) {
	autoOrNot, _ := strconv.Atoi(r.FormValue("autoornot"))
	business := -1
	var port int
	if autoOrNot == 1 && appConf.BusinessList != "" {
		business, _ = strconv.Atoi(r.FormValue("business"))
	}
	if autoOrNot == 0 {
		port, _ = strconv.Atoi(r.FormValue("port"))
	}
	servers := r.FormValue("servers")
	backupServers := r.FormValue("backup_servers")
	comment := strings.TrimSpace(r.FormValue("comment"))
	logOrNot := r.FormValue("logornot")

	rows, err := db.QueryVPort()
	if err != nil {
		logger.Println(err)
	}
	rowNum := len(rows)

	vportToAssign := -1

	dupOrNot := 0
	noAvailablePort := false

	// 若是指定端口方式,则判断指定的端口是否在1000-99999范围内
	inPortRange := true
	if autoOrNot == 0 && port < 1000 || port > 99999 {
		inPortRange = false
	}

	if inPortRange == true {
		/*
			将1000到已分配的最大端口号之间所有未占用和已占用的端口映射到一个真假值数组
		*/
		var portSlots []bool
		var assignedBiggest int
		if rowNum > 0 {
			assignedBiggest = rows[rowNum-1]
			allowedSmallest := 1000
			mayAssignedPortRange := assignedBiggest - allowedSmallest + 1
			//fmt.Println(mayAssignedPortRange)
			portSlots = make([]bool, mayAssignedPortRange)
			/*
			* 注意上一句make的用法-容量和长度都为mayAssignedPortRange,
			* 并且所有bool类型元素都自动初始化为false,所以下面的几行初始化代码不再需要。
			 */
			/*
				fmt.Println(portSlots[0])
				fmt.Println(portSlots[1])
				fmt.Println(portSlots[mayAssignedPortRange-1])
				for index := 0; index < mayAssignedPortRange; index++ {
					portSlots[index] = false
				}
			*/
			for index := 0; index < rowNum; index++ {
				port := rows[index]
				portSlots[port-1000] = true
			}
		}
		// 自动分配端口
		if autoOrNot == 1 {
			// 未指定业务
			if business == -1 {
				/*
					虚拟ip端口自动分配算法(不指定业务)
					可分配端口范围:10000 - 19999
				*/
				if rowNum == 0 {
					vportToAssign = 10000
				} else {
					vportToAssign, noAvailablePort = autoAssignPort(10000, 19999, assignedBiggest, portSlots)
				}
			} else {
				// 指定业务
				var portRange string
				businesses := strings.Split(appConf.BusinessList, ";")
				for index, bToPortRange := range businesses {
					if index == business {
						thisBToPortRange := strings.Split(bToPortRange, ",")
						if comment != "" {
							comment += "<br />"
						}
						comment += "业务:" + thisBToPortRange[0]
						portRange = thisBToPortRange[1]
						break
					}
				}
				firstAndLast := strings.Split(portRange, "-")
				firstPort, _ := strconv.Atoi(firstAndLast[0])
				lastPort, _ := strconv.Atoi(firstAndLast[1])
				if rowNum == 0 {
					vportToAssign = firstPort
				} else {
					vportToAssign, noAvailablePort = autoAssignPort(firstPort, lastPort, assignedBiggest, portSlots)
				}
			}
		} else {
			// 指定端口
			// 检测端口是否已被占用
			for _, vport := range rows {
				if port == vport {
					dupOrNot = 1
					break
				}
			}
			if dupOrNot == 0 {
				vportToAssign = port
			}
		}
	}

	var result statusResult

	if inPortRange == false {
		result = statusResult{
			Success: "false",
			Msg:     "指定的端口不在1000-99999的范围内!",
		}
	} else {
		if dupOrNot == 0 && noAvailablePort == false {
			now := time.Now().Format("2006-01-02 15:04:05")
			logornot, _ := strconv.Atoi(logOrNot)
			//fmt.Printf("servers: %s, backupServers: %s, vportToAssign: %d, comment: %s, logornot: %d, now: %s", servers, backupServers, vportToAssign, comment, logornot, now)
			err = db.InsertNewTask(servers, backupServers, vportToAssign, comment, logornot, now)
			if err != nil {
				logger.Println(err)
			}
			messageParts := make([]string, 0, 2)
			messageParts = append(messageParts, appConf.Vip)
			messageParts = append(messageParts, strconv.Itoa(vportToAssign))
			message := strings.Join(messageParts, ":")

			result = statusResult{
				Success: "true",
				Msg:     message,
			}
		} else if dupOrNot != 0 {
			result = statusResult{
				Success: "false",
				Msg:     "端口已被占用,请选择指定其他端口!",
			}
		} else {
			result = statusResult{
				Success: "false",
				Msg:     "该业务已没有可用的端口!",
			}
		}
	}
	rt, err := json.Marshal(result)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Fprintf(w, string(rt))
	return
}
Ejemplo n.º 7
0
func CaseHandler(w http.ResponseWriter, r *auth.AuthenticatedRequest) {
	var err error
	path := r.URL.Path
	pattern, err := regexp.Compile("/case/([^/]*)")
	if err != nil {
		panic(err)
	}
	matches := pattern.FindStringSubmatch(path)
	if len(matches) != 2 {
		resourceNotFound(w, &r.Request)
		return
	}
	id := matches[1]

	switch r.Method {
	case "GET":
		baileyCase := record.FetchRecord(id)
		if baileyCase == nil {
			resourceNotFound(w, &r.Request)
			return
		}
		responseBody := mustache.RenderFile("view/case.html", baileyCase)
		w.Write([]byte(responseBody))

	case "POST":
		baileyCase := record.FetchRecord(id)
		if baileyCase == nil {
			resourceNotFound(w, &r.Request)
			return
		}
		var jsonUpdate JsonUpdate
		err = json.Unmarshal([]byte(r.FormValue("json")), &jsonUpdate)
		if err != nil {
			log.Println(err)
			badRequest(w, &r.Request)
			return
		}

		// this is really ugly code, and should be fixed asap
		baileyCase.OfInterest = jsonUpdate.OfInterest
		baileyCase.NotOfInterest = jsonUpdate.NotOfInterest
		baileyCase.Clothing = jsonUpdate.Clothing
		baileyCase.ClothingCount = jsonUpdate.ClothingCount
		baileyCase.RawTextiles = jsonUpdate.RawTextiles
		baileyCase.RawTextilesCount = jsonUpdate.RawTextilesCount
		baileyCase.OtherTextiles = jsonUpdate.OtherTextiles
		baileyCase.Accessories = jsonUpdate.Accessories
		baileyCase.AccessoriesCount = jsonUpdate.AccessoriesCount
		baileyCase.HouseholdLinen = jsonUpdate.HouseholdLinen
		baileyCase.HouseholdLinenCount = jsonUpdate.HouseholdLinenCount
		baileyCase.Other = jsonUpdate.Other
		baileyCase.OtherCount = jsonUpdate.OtherCount
		baileyCase.OtherNotSpecified = jsonUpdate.OtherNotSpecified

		baileyCase.Save()
		successNoContent(w, &r.Request)

	default:
		methodNotAllowed(w, &r.Request)
	}
}
Ejemplo n.º 8
0
func insertHandler(w http.ResponseWriter, r *auth.AuthenticatedRequest) {
	file, header, err := r.FormFile("file")
	if err != nil {
		log.Error("Invalid form data %v:%s", r.Header, err.Error())
		fmt.Fprintln(w, err)
		return
	}
	log.Debug("Insert handler started for file %s", header.Filename)
	tag := r.Request.Header.Get("File-Tag")
	if len(tag) == 0 {
		log.Error("No file-tag header")
		fmt.Fprintf(w, "No file-tag header")
		return
	}

	bytes, err := base64.StdEncoding.DecodeString(header.Filename)
	if err != nil {
		log.Error("Filename %s is not valid base64 string", header.Filename)
		fmt.Fprintf(w, "Filename is not valid base64 string")
		return
	}
	filename := string(bytes)

	id, err := RegisterFile(filename, tag, time.Now())
	if err != nil {
		log.Error("Unable to register file %s from %s in DB:%s", filename, r.Host, err.Error())
		fmt.Fprintf(w, "Unable to register file")
		return
	}

	path, dir, err := CreateFilePath(id)

	if err != nil {
		log.Error("Unable to create file path for %s from %s in DB:%s", filename, r.Host, err.Error())
		fmt.Fprintf(w, "Unable to create file path")
		return
	}

	out, err := os.Create(path)
	if err != nil {
		log.Error("Unable to save file %s from %s in DB:%s", filename, r.Host, err.Error())
		fmt.Fprintf(w, "Unable to save file")
		return
	}

	_, err = io.Copy(out, file)
	if err != nil {
		fmt.Fprintln(w, err)
	}

	out.Close()
	file.Close()
	err = SaveMetaData(id, filename, tag, dir)
	if err != nil {
		log.Error("can't save meta for %d:%s", id, err.Error())
	}
	err = ConfirmFile(id)
	if err != nil {
		log.Error("Unable to commit file %s from %s in DB:%s", filename, r.Host, err.Error())
		fmt.Fprintf(w, "Unable to commit file")
		return
	}
	w.Header().Add("File-Id", strconv.FormatInt(id, 10))
	fmt.Fprintf(w, "%d", id)
	log.Info("File %s from %s saved succesfully", filename, r.Host)
}