Exemplo n.º 1
0
func UploadDevice(ctx context.Context, w rest.ResponseWriter, r *rest.Request) {
	w.Header().Add("Content-type", "text/html; charset=utf-8")
	r.ParseForm()
	file, handle, err := r.FormFile("file")
	if err != nil {
		w.Write([]byte("{\"Message\":\"" + err.Error() + "\",\"Status\":\"error\"}"))
		return
	}

	cd, err := iconv.Open("UTF-8", "GBK")
	if err != nil {
		w.Write([]byte("{\"Message\":\"" + err.Error() + "\",\"Status\":\"error\"}"))
		return
	}
	defer cd.Close()

	dir := "/tmp/cloudboot-server/"
	if !util.FileExist(dir) {
		err := os.MkdirAll(dir, 0777)
		if err != nil {
			w.Write([]byte("{\"Message\":\"" + err.Error() + "\",\"Status\":\"error\"}"))
			return
		}
	}

	list := strings.Split(handle.Filename, ".")
	fix := list[len(list)-1]

	h := md5.New()
	h.Write([]byte(fmt.Sprintf("%s", time.Now().UnixNano()) + handle.Filename))
	cipherStr := h.Sum(nil)
	md5 := fmt.Sprintf("%s", hex.EncodeToString(cipherStr))
	filename := "osinstall-upload-" + md5 + "." + fix

	result := make(map[string]interface{})
	result["result"] = filename

	if util.FileExist(dir + filename) {
		os.Remove(dir + filename)
	}

	f, err := os.OpenFile(dir+filename, os.O_WRONLY|os.O_CREATE, 0666)
	io.Copy(f, file)
	if err != nil {
		w.Write([]byte("{\"Message\":\"" + err.Error() + "\",\"Status\":\"error\"}"))
		return
	}
	defer f.Close()
	defer file.Close()

	data := map[string]interface{}{"Status": "success", "Message": "操作成功", "Content": result}
	json, err := json.Marshal(data)
	if err != nil {
		w.Write([]byte("{\"Message\":\"" + err.Error() + "\",\"Status\":\"error\"}"))
		return
	}
	w.Write([]byte(json))
	return
}
Exemplo n.º 2
0
func UploadDevice(ctx context.Context, w rest.ResponseWriter, r *rest.Request) {
	r.ParseForm()
	file, handle, err := r.FormFile("file")
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
		return
	}

	cd, err := iconv.Open("UTF-8", "GBK")
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "参数错误" + err.Error()})
		return
	}
	defer cd.Close()

	dir := "./upload/"
	if !util.FileExist(dir) {
		err := os.MkdirAll(dir, 0777)
		if err != nil {
			w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
			return
		}
	}

	list := strings.Split(handle.Filename, ".")
	fix := list[len(list)-1]

	h := md5.New()
	h.Write([]byte(fmt.Sprintf("%s", time.Now().UnixNano()) + handle.Filename))
	cipherStr := h.Sum(nil)
	md5 := fmt.Sprintf("%s", hex.EncodeToString(cipherStr))
	filename := md5 + "." + fix

	result := make(map[string]interface{})
	result["result"] = filename

	if util.FileExist(dir + filename) {
		os.Remove(dir + filename)
	}

	f, err := os.OpenFile(dir+filename, os.O_WRONLY|os.O_CREATE, 0666)
	io.Copy(f, file)
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
		return
	}
	defer f.Close()
	defer file.Close()
	w.WriteJSON(map[string]interface{}{"Status": "success", "Message": "操作成功", "Content": result})
	return
}
Exemplo n.º 3
0
func runServer(c *cli.Context) {
	if !util.FileExist(configFile) {
		fmt.Println("The config file(" + configFile + ") is not exist!")
		return
	}

	srvr, err := osinstallserver.NewServer(configFile, osinstallserver.DevPipeline)
	if err != nil {
		srvr.Log.Error(err)
		return
	}

	addr := ":8083"

	l4, err := net.Listen("tcp4", addr)
	if err != nil {
		srvr.Log.Error(err)
		return
	}

	srvr.Log.Info("The server is running.")

	//cron
	route.CloudBootCron(srvr.Conf, srvr.Log, srvr.Repo)

	if err := http.Serve(l4, srvr); err != nil {
		srvr.Log.Error(err)
		return
	}
}
Exemplo n.º 4
0
//create noVNC token file
func RunCreateVmNoVncTokenFile(repo model.Repo, logger logger.Logger, vmDeviceId uint) error {
	vmDevice, err := repo.GetVmDeviceById(vmDeviceId)
	if err != nil {
		return err
	}

	device, err := repo.GetDeviceById(vmDevice.DeviceID)
	if err != nil {
		return err
	}

	var newHostname = strings.Replace(vmDevice.Hostname, ":", "_", -1)
	var strFormat = `%s: %s:%s`
	var str = fmt.Sprintf(strFormat,
		newHostname,
		device.Ip,
		vmDevice.VncPort)

	var dir = "/etc/cloudboot-server/novnc-tokens"
	var file = vmDevice.Hostname

	if !util.FileExist(dir) {
		err := os.MkdirAll(dir, 0777)
		if err != nil {
			return err
		}
	}
	//文件已存在,先删除
	if util.FileExist(dir + "/" + file) {
		err := os.Remove(dir + "/" + file)
		if err != nil {
			return err
		}
	}
	logger.Debugf("create vm novnc token file %s:%s", dir+"/"+file, str)
	bytes := []byte(str)
	errCreate := ioutil.WriteFile(dir+"/"+file, bytes, 0644)
	if errCreate != nil {
		logger.Errorf("error:%s", errCreate.Error())
		return errCreate
	}
	return nil
}
Exemplo n.º 5
0
//delete noVNC token file
func RunDeleteVmNoVncTokenFile(repo model.Repo, logger logger.Logger, vmDeviceId uint) error {
	vmDevice, err := repo.GetVmDeviceById(vmDeviceId)
	if err != nil {
		return err
	}

	var dir = "/etc/cloudboot-server/novnc-tokens"
	var file = vmDevice.Hostname
	logger.Debugf("delete vm novnc token file:%s", dir+"/"+file)
	if util.FileExist(dir + "/" + file) {
		err := os.Remove(dir + "/" + file)
		if err != nil {
			logger.Errorf("error:%s", err.Error())
			return err
		}
	}
	return nil
}
Exemplo n.º 6
0
func UploadHardware(ctx context.Context, w rest.ResponseWriter, r *rest.Request) {
	r.ParseForm()
	file, handle, err := r.FormFile("file")
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
		return
	}

	cd, err := iconv.Open("UTF-8", "GBK")
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "参数错误" + err.Error()})
		return
	}
	defer cd.Close()

	dir := "./upload/"
	if !util.FileExist(dir) {
		err := os.MkdirAll(dir, 0777)
		if err != nil {
			w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
			return
		}
	}

	list := strings.Split(handle.Filename, ".")
	fix := list[len(list)-1]

	h := md5.New()
	h.Write([]byte(fmt.Sprintf("%s", time.Now().UnixNano()) + handle.Filename))
	cipherStr := h.Sum(nil)
	md5 := fmt.Sprintf("%s", hex.EncodeToString(cipherStr))
	filename := md5 + "." + fix

	result := make(map[string]interface{})
	result["result"] = filename

	if util.FileExist(dir + filename) {
		os.Remove(dir + filename)
	}

	f, err := os.OpenFile(dir+filename, os.O_WRONLY|os.O_CREATE, 0666)
	io.Copy(f, file)
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
		return
	}
	defer f.Close()
	defer file.Close()

	fileHandle, err := os.Open(dir + filename)
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
		return
	}
	var data []map[string]interface{}
	bytes, err := ioutil.ReadAll(fileHandle)
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
		return
	}
	errDecode := json.Unmarshal(bytes, &data)
	if errDecode != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "文件格式错误:" + errDecode.Error()})
		return
	}
	for _, v := range data {
		if v["Company"] == "" || v["ModelName"] == "" {
			w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "文件格式错误!"})
			return
		}
	}

	repo, ok := middleware.RepoFromContext(ctx)
	if !ok {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "内部服务器错误"})
		return
	}

	for _, v := range data {
		var info struct {
			Company     string
			Product     string
			ModelName   string
			Raid        string
			Oob         string
			Bios        string
			IsSystemAdd string
			Tpl         string
			Data        string
			Source      string
			Version     string
			Status      string
		}

		info.Company = strings.TrimSpace(v["Company"].(string))
		info.Product = strings.TrimSpace(v["Product"].(string))
		info.ModelName = strings.TrimSpace(v["ModelName"].(string))
		info.IsSystemAdd = "Yes"
		info.Tpl = strings.TrimSpace(v["Tpl"].(string))
		info.Data = strings.TrimSpace(v["Data"].(string))
		info.Source = strings.TrimSpace(info.Source)
		info.Version = strings.TrimSpace(info.Version)
		info.Status = "Success"

		where := "company = '" + info.Company + "' and product = '" + info.Product + "' and model_name = '" + info.ModelName + "' and is_system_add = 'Yes'"

		count, err := repo.CountHardwareByWhere(where)
		if err != nil {
			w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
			return
		}

		if count > 0 {
			hardware, err := repo.GetHardwareByWhere(where)
			if err != nil {
				w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
				return
			}
			var isUpdate bool
			isUpdate = false
			if hardware.Data != info.Data {
				isUpdate = true
			}
			if hardware.Tpl != info.Tpl {
				isUpdate = true
			}
			if isUpdate == true {
				_, err := repo.UpdateHardwareById(hardware.ID, info.Company, info.Product, info.ModelName, info.Raid, info.Oob, info.Bios, info.Tpl, info.Data, info.Source, info.Version, info.Status)
				if err != nil {
					w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
					return
				}
			}
		} else {
			_, errAdd := repo.AddHardware(info.Company, info.Product, info.ModelName, info.Raid, info.Oob, info.Bios, info.IsSystemAdd, info.Tpl, info.Data, info.Source, info.Version, info.Status)
			if errAdd != nil {
				w.WriteJSON(map[string]interface{}{"Status": "error", "Message": errAdd.Error()})
				return
			}
		}
	}
	//delete tmp file
	errDeleteFile := os.Remove(dir + filename)
	if errDeleteFile != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": errDeleteFile.Error()})
		return
	}

	w.WriteJSON(map[string]interface{}{"Status": "success", "Message": "操作成功", "Content": result})
	return
}
Exemplo n.º 7
0
//上报安装进度
func ReportInstallInfo(ctx context.Context, w rest.ResponseWriter, r *rest.Request) {
	w.Header().Add("Content-type", "application/json; charset=utf-8")
	repo, ok := middleware.RepoFromContext(ctx)
	if !ok {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "内部服务器错误"})
		return
	}

	conf, ok := middleware.ConfigFromContext(ctx)
	if !ok {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "内部服务器错误"})
		return
	}

	if conf.OsInstall.PxeConfigDir == "" {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "Pxe配置文件目录没有指定"})
		return
	}

	var info struct {
		Sn              string
		Title           string
		InstallProgress float64
		InstallLog      string
	}

	if err := r.DecodeJSONPayload(&info); err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "参数错误"})
		return
	}

	info.Sn = strings.TrimSpace(info.Sn)
	info.Title = strings.TrimSpace(info.Title)
	if info.Sn == "" {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "SN参数不能为空!"})
		return
	}

	deviceId, err := repo.GetDeviceIdBySn(info.Sn)
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "该设备不存在!"})
		return
	}

	device, err := repo.GetDeviceById(deviceId)
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
		return
	}

	var status string
	var logTitle string

	if info.InstallProgress == -1 {
		status = "failure"
		info.InstallProgress = 0
		logTitle = info.Title
	} else if info.InstallProgress >= 0 && info.InstallProgress < 1 {
		status = "installing"
		logTitle = info.Title + "(" + fmt.Sprintf("安装进度 %.1f", info.InstallProgress*100) + "%)"
	} else if info.InstallProgress == 1 {
		status = "success"
		logTitle = info.Title + "(" + fmt.Sprintf("安装进度 %.1f", info.InstallProgress*100) + "%)"
		//logTitle = "安装成功"
	} else {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "安装进度参数不正确!"})
		return
	}

	/*
		if device.InstallLog != "" {
			info.InstallLog = device.InstallLog + "\n" + info.InstallLog
		}
	*/
	_, errUpdate := repo.UpdateInstallInfoById(device.ID, status, info.InstallProgress)
	if errUpdate != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": errUpdate.Error()})
		return
	}

	//删除PXE配置文件
	if info.InstallProgress == 1 {
		macs, err := repo.GetMacListByDeviceID(device.ID)
		if err != nil {
			w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
			return
		}
		for _, mac := range macs {
			pxeFileName := util.GetPxeFileNameByMac(mac.Mac)
			confDir := conf.OsInstall.PxeConfigDir
			if util.FileExist(confDir + "/" + pxeFileName) {
				err := os.Remove(confDir + "/" + pxeFileName)
				if err != nil {
					w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
					return
				}
			}
		}
	}

	var installLog string
	byteDecode, err := base64.StdEncoding.DecodeString(info.InstallLog)
	if err != nil {
		installLog = ""
	} else {
		installLog = string(byteDecode)
	}

	_, errAddLog := repo.AddDeviceLog(device.ID, logTitle, "install", installLog)
	if errAddLog != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": errAddLog.Error()})
		return
	}

	result := make(map[string]string)
	result["Result"] = "true"
	w.WriteJSON(map[string]interface{}{"Status": "success", "Message": "操作成功", "Content": result})
}
Exemplo n.º 8
0
func ImportDevice(ctx context.Context, w rest.ResponseWriter, r *rest.Request) {
	repo, ok := middleware.RepoFromContext(ctx)
	if !ok {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "内部服务器错误"})
		return
	}

	session, err := GetSession(w, r)
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "参数错误" + err.Error()})
		return
	}

	var info struct {
		Filename string
	}
	if err := r.DecodeJSONPayload(&info); err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "参数错误" + err.Error()})
		return
	}

	file := "/tmp/cloudboot-server/" + info.Filename

	cd, err := iconv.Open("utf-8", "gbk") // convert gbk to utf8
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "参数错误" + err.Error()})
		return
	}
	defer cd.Close()

	input, err := os.Open(file)
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "参数错误" + err.Error()})
		return
	}
	bufSize := 1024 * 1024
	read := iconv.NewReader(cd, input, bufSize)

	r2 := csv.NewReader(read)
	ra, err := r2.ReadAll()
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "参数错误" + err.Error()})
		return
	}

	length := len(ra)

	type Device struct {
		ID              uint
		BatchNumber     string
		Sn              string
		Hostname        string
		Ip              string
		ManageIp        string
		NetworkID       uint
		ManageNetworkID uint
		OsID            uint
		HardwareID      uint
		SystemID        uint
		Location        string
		LocationID      uint
		AssetNumber     string
		Status          string
		InstallProgress float64
		InstallLog      string
		NetworkName     string
		OsName          string
		HardwareName    string
		SystemName      string
		Content         string
		IsSupportVm     string
		UserID          uint
	}

	batchNumber, err := repo.CreateBatchNumber()
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
		return
	}
	//var result []string
	for i := 1; i < length; i++ {
		//result = append(result, ra[i][0])
		var row Device

		if len(ra[i]) != 10 {
			continue
		}

		row.Sn = strings.TrimSpace(ra[i][0])
		row.Hostname = strings.TrimSpace(ra[i][1])
		row.Ip = strings.TrimSpace(ra[i][2])
		row.OsName = strings.TrimSpace(ra[i][3])
		row.HardwareName = strings.TrimSpace(ra[i][4])
		row.SystemName = strings.TrimSpace(ra[i][5])
		row.Location = strings.TrimSpace(ra[i][6])
		row.AssetNumber = strings.TrimSpace(ra[i][7])
		row.ManageIp = strings.TrimSpace(ra[i][8])
		row.IsSupportVm = strings.TrimSpace(ra[i][9])
		row.UserID = session.ID

		if len(row.Sn) > 255 {
			var br string
			if row.Content != "" {
				br = "<br />"
			}
			row.Content += br + "SN长度超过255限制!"
		}

		if len(row.Hostname) > 255 {
			var br string
			if row.Content != "" {
				br = "<br />"
			}
			row.Content += br + "主机名长度超过255限制!"
		}

		if len(row.Location) > 255 {
			var br string
			if row.Content != "" {
				br = "<br />"
			}
			row.Content += br + "位置长度超过255限制!"
		}

		if len(row.AssetNumber) > 255 {
			var br string
			if row.Content != "" {
				br = "<br />"
			}
			row.Content += br + "财编长度超过255限制!"
		}

		if row.Sn == "" {
			var br string
			if row.Content != "" {
				br = "<br />"
			}
			row.Content += br + "SN不能为空!"
		}

		if row.Hostname == "" {
			var br string
			if row.Content != "" {
				br = "<br />"
			}
			row.Content += br + "主机名不能为空!"
		}

		if row.Ip == "" {
			var br string
			if row.Content != "" {
				br = "<br />"
			}
			row.Content += br + "IP不能为空!"
		}

		if row.OsName == "" {
			var br string
			if row.Content != "" {
				br = "<br />"
			}
			row.Content += br + "操作系统不能为空!"
		}

		if row.SystemName == "" {
			var br string
			if row.Content != "" {
				br = "<br />"
			}
			row.Content += br + "系统安装模板不能为空!"
		}

		if row.Location == "" {
			var br string
			if row.Content != "" {
				br = "<br />"
			}
			row.Content += br + "位置不能为空!"
		}

		if row.IsSupportVm != "" && row.IsSupportVm != "Yes" && row.IsSupportVm != "No" {
			var br string
			if row.Content != "" {
				br = "<br />"
			}
			row.Content += br + "是否支持虚拟机的参数格式不正确!"
		}

		if row.IsSupportVm != "Yes" {
			row.IsSupportVm = "No"
		}

		//match manufacturer
		countManufacturer, errCountManufacturer := repo.CountManufacturerBySn(row.Sn)
		if errCountManufacturer != nil {
			w.WriteJSON(map[string]interface{}{"Status": "error", "Message": errCountManufacturer.Error()})
			return
		}
		if countManufacturer <= 0 {
			var br string
			if row.Content != "" {
				br = "<br />"
			}
			row.Content += br + "未在【资源池管理】里匹配到该SN,请先将该设备加电并进入BootOS!"
		}
		if countManufacturer > 0 {
			//validate user from manufacturer
			manufacturer, err := repo.GetManufacturerBySn(row.Sn)
			if err != nil {
				w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "参数错误" + err.Error()})
				return
			}
			if session.Role != "Administrator" && manufacturer.UserID != session.ID {
				var br string
				if row.Content != "" {
					br = "<br />"
				}
				row.Content += br + "您无权操作其他人的设备!"
			}
		}

		//validate ip from vm device
		countVmIp, errVmIp := repo.CountVmDeviceByIp(row.Ip)
		if errVmIp != nil {
			w.WriteJSON(map[string]interface{}{"Status": "error", "Message": errVmIp.Error()})
			return
		}
		if countVmIp > 0 {
			var br string
			if row.Content != "" {
				br = "<br />"
			}
			row.Content += br + row.Ip + " 该IP已被虚拟机使用!"
		}

		countDevice, err := repo.CountDeviceBySn(row.Sn)
		if err != nil {
			w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
			return
		}

		if countDevice > 0 {
			ID, err := repo.GetDeviceIdBySn(row.Sn)
			row.ID = ID
			if err != nil {
				w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
				return
			}

			device, err := repo.GetDeviceBySn(row.Sn)
			if err != nil {
				w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "参数错误" + err.Error()})
				return
			}

			if session.Role != "Administrator" && device.UserID != session.ID {
				var br string
				if row.Content != "" {
					br = "<br />"
				}
				row.Content += br + "SN:" + row.Sn + " 该设备已被录入,不能重复录入!"
			}

			//hostname
			countHostname, err := repo.CountDeviceByHostnameAndId(row.Hostname, ID)
			if err != nil {
				w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "参数错误:" + err.Error()})
				return
			}
			if countHostname > 0 {
				var br string
				if row.Content != "" {
					br = "<br />"
				}
				row.Content += br + "SN:" + row.Sn + "该主机名已存在!"
			}

			//IP
			countIp, err := repo.CountDeviceByIpAndId(row.Ip, ID)
			if err != nil {
				w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
				return
			}

			if countIp > 0 {
				var br string
				if row.Content != "" {
					br = "<br />"
				}
				row.Content += br + "SN:" + row.Sn + "该IP已存在!"
			}

			if row.ManageIp != "" {
				//IP
				countManageIp, err := repo.CountDeviceByManageIpAndId(row.ManageIp, ID)
				if err != nil {
					w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
					return
				}

				if countManageIp > 0 {
					var br string
					if row.Content != "" {
						br = "<br />"
					}
					row.Content += br + "SN:" + row.Sn + "该管理IP已存在!"
				}
			}

			//validate host server info
			countVm, errVm := repo.CountVmDeviceByDeviceId(row.ID)
			if errVm != nil {
				w.WriteJSON(map[string]interface{}{"Status": "error", "Message": errVm.Error()})
				return
			}
			if countVm > 0 {
				var br string
				if row.Content != "" {
					br = "<br />"
				}
				row.Content += br + "该物理机下(SN:" + device.Sn + ")还存留有虚拟机,不允许修改信息。请先销毁虚拟机后再操作!"
			}
		} else {
			//hostname
			countHostname, err := repo.CountDeviceByHostname(row.Hostname)
			if err != nil {
				w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "参数错误:" + err.Error()})
				return
			}
			if countHostname > 0 {
				var br string
				if row.Content != "" {
					br = "<br />"
				}
				row.Content += br + "SN:" + row.Sn + "该主机名已存在!"
			}

			//IP
			countIp, err := repo.CountDeviceByIp(row.Ip)
			if err != nil {
				w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
				return
			}

			if countIp > 0 {
				var br string
				if row.Content != "" {
					br = "<br />"
				}
				row.Content += br + "SN:" + row.Sn + "该IP已存在!"
			}

			if row.ManageIp != "" {
				//IP
				countManageIp, err := repo.CountDeviceByManageIp(row.ManageIp)
				if err != nil {
					w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
					return
				}

				if countManageIp > 0 {
					var br string
					if row.Content != "" {
						br = "<br />"
					}
					row.Content += br + "SN:" + row.Sn + "该管理IP已存在!"
				}
			}
		}

		//匹配网络
		isValidate, err := regexp.MatchString("^((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)$", row.Ip)
		if err != nil {
			w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "参数错误" + err.Error()})
			return
		}

		if !isValidate {
			var br string
			if row.Content != "" {
				br = "<br />"
			}
			row.Content += br + "SN:" + row.Sn + "IP格式不正确!"
		}

		modelIp, err := repo.GetIpByIp(row.Ip)
		if err != nil {
			var br string
			if row.Content != "" {
				br = "<br />"
			}
			row.Content += br + "SN:" + row.Sn + "未匹配到网段!"
		}

		_, errNetwork := repo.GetNetworkById(modelIp.NetworkID)
		if errNetwork != nil {
			var br string
			if row.Content != "" {
				br = "<br />"
			}
			row.Content += br + "SN:" + row.Sn + "未匹配到网段!"
		}

		row.NetworkID = modelIp.NetworkID

		if row.ManageIp != "" {
			//匹配网络
			isValidate, err := regexp.MatchString("^((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)$", row.ManageIp)
			if err != nil {
				w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "参数错误" + err.Error()})
				return
			}

			if !isValidate {
				var br string
				if row.Content != "" {
					br = "<br />"
				}
				row.Content += br + "SN:" + row.Sn + "管理IP格式不正确!"
			}

			modelIp, err := repo.GetManageIpByIp(row.ManageIp)
			if err != nil {
				var br string
				if row.Content != "" {
					br = "<br />"
				}
				row.Content += br + "SN:" + row.Sn + "未匹配到管理网段!"
			}

			_, errNetwork := repo.GetManageNetworkById(modelIp.NetworkID)
			if errNetwork != nil {
				var br string
				if row.Content != "" {
					br = "<br />"
				}
				row.Content += br + "SN:" + row.Sn + "未匹配到管理网段!"
			}

			row.ManageNetworkID = modelIp.NetworkID
		}

		//OSName
		countOs, err := repo.CountOsConfigByName(row.OsName)
		if err != nil {
			w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
			return
		}

		if countOs <= 0 {
			var br string
			if row.Content != "" {
				br = "<br />"
			}
			row.Content += br + "SN:" + row.Sn + "未匹配到操作系统!"
		}
		mod, err := repo.GetOsConfigByName(row.OsName)
		if err != nil {
			w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
			return
		}
		row.OsID = mod.ID

		//SystemName
		countSystem, err := repo.CountSystemConfigByName(row.SystemName)
		if err != nil {
			w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
			return
		}

		if countSystem <= 0 {
			var br string
			if row.Content != "" {
				br = "<br />"
			}
			row.Content += br + "SN:" + row.Sn + "未匹配到系统安装模板!"
		}

		systemId, err := repo.GetSystemConfigIdByName(row.SystemName)
		if err != nil {
			w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
			return
		}
		row.SystemID = systemId

		if row.HardwareName != "" {
			//HardwareName
			countHardware, err := repo.CountHardwareWithSeparator(row.HardwareName)
			if err != nil {
				w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
				return
			}

			if countHardware <= 0 {
				var br string
				if row.Content != "" {
					br = "<br />"
				}
				row.Content += br + "SN:" + row.Sn + "未匹配到硬件配置模板!"
			}

			hardware, err := repo.GetHardwareBySeaprator(row.HardwareName)
			if err != nil {
				w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
				return
			}
			row.HardwareID = hardware.ID
		}

		if row.HardwareID > uint(0) {
			hardware, err := repo.GetHardwareById(row.HardwareID)
			if err != nil {
				w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
				return
			}
			if hardware.Data != "" {
				if strings.Contains(hardware.Data, "<{manage_ip}>") || strings.Contains(hardware.Data, "<{manage_netmask}>") || strings.Contains(hardware.Data, "<{manage_gateway}>") {
					if row.ManageIp == "" || row.ManageNetworkID <= uint(0) {
						var br string
						if row.Content != "" {
							br = "<br />"
						}
						row.Content += br + "SN:" + row.Sn + "硬件配置模板的OOB网络类型为静态IP的方式,请填写管理IP!"
					}
				}
			}
		}

		if row.Location != "" {
			countLocation, err := repo.CountLocationByName(row.Location)
			if err != nil {
				w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
				return
			}
			if countLocation > 0 {
				locationId, err := repo.GetLocationIdByName(row.Location)
				if err != nil {
					w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
					return
				}
				row.LocationID = locationId
			}
			if row.LocationID <= uint(0) {
				/*
					var br string
					if row.Content != "" {
						br = "<br />"
					}
					row.Content += br + "SN:" + row.Sn + " 未匹配到位置!"
				*/
				locationId, err := repo.ImportLocation(row.Location)
				if err != nil {
					w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
					return
				}

				if locationId <= uint(0) {
					var br string
					if row.Content != "" {
						br = "<br />"
					}
					row.Content += br + "SN:" + row.Sn + " 未匹配到位置!"
				}
				row.LocationID = locationId

			}
		}
		if row.Content != "" {
			w.WriteJSON(map[string]interface{}{"Status": "error", "Message": row.Content})
			return
		} else {
			status := "pre_install"
			if countDevice > 0 {
				id, err := repo.GetDeviceIdBySn(row.Sn)
				if err != nil {
					w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
					return
				}

				deviceOld, err := repo.GetDeviceById(id)
				if err != nil {
					w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
					return
				}

				_, errLog := repo.UpdateDeviceLogTypeByDeviceIdAndType(id, "install", "install_history")
				if errLog != nil {
					w.WriteJSON(map[string]interface{}{"Status": "error", "Message": errLog.Error()})
					return
				}

				//init manufactures device_id
				countManufacturer, errCountManufacturer := repo.CountManufacturerBySn(row.Sn)
				if errCountManufacturer != nil {
					w.WriteJSON(map[string]interface{}{"Status": "error", "Message": errCountManufacturer.Error()})
					return
				}
				if countManufacturer > 0 {
					manufacturerId, errGetManufacturerBySn := repo.GetManufacturerIdBySn(row.Sn)
					if errGetManufacturerBySn != nil {
						w.WriteJSON(map[string]interface{}{"Status": "error", "Message": errGetManufacturerBySn.Error()})
						return
					}
					_, errUpdate := repo.UpdateManufacturerDeviceIdById(manufacturerId, id)
					if errUpdate != nil {
						w.WriteJSON(map[string]interface{}{"Status": "error", "Message": errUpdate.Error()})
						return
					}
				}

				//delete host server info
				_, errDeleteHost := repo.DeleteVmHostBySn(deviceOld.Sn)
				if errDeleteHost != nil {
					w.WriteJSON(map[string]interface{}{"Status": "error", "Message": errDeleteHost.Error()})
					return
				}

				device, errUpdate := repo.UpdateDeviceById(id, batchNumber, row.Sn, row.Hostname, row.Ip, row.ManageIp, row.NetworkID, row.ManageNetworkID, row.OsID, row.HardwareID, row.SystemID, "", row.LocationID, row.AssetNumber, status, row.IsSupportVm, row.UserID)
				if errUpdate != nil {
					w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "操作失败:" + errUpdate.Error()})
					return
				}

				//log
				logContent := make(map[string]interface{})
				logContent["data_old"] = deviceOld
				logContent["data"] = device

				json, err := json.Marshal(logContent)
				if err != nil {
					w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "操作失败:" + err.Error()})
					return
				}

				_, errAddLog := repo.AddDeviceLog(device.ID, "修改设备信息", "operate", string(json))
				if errAddLog != nil {
					w.WriteJSON(map[string]interface{}{"Status": "error", "Message": errAddLog.Error()})
					return
				}
			} else {
				device, err := repo.AddDevice(batchNumber, row.Sn, row.Hostname, row.Ip, row.ManageIp, row.NetworkID, row.ManageNetworkID, row.OsID, row.HardwareID, row.SystemID, "", row.LocationID, row.AssetNumber, status, row.IsSupportVm, row.UserID)
				if err != nil {
					w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "操作失败:" + err.Error()})
					return
				}

				//log
				logContent := make(map[string]interface{})
				logContent["data"] = device
				json, err := json.Marshal(logContent)
				if err != nil {
					w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "操作失败:" + err.Error()})
					return
				}

				_, errAddLog := repo.AddDeviceLog(device.ID, "录入新设备", "operate", string(json))
				if errAddLog != nil {
					w.WriteJSON(map[string]interface{}{"Status": "error", "Message": errAddLog.Error()})
					return
				}

				//init manufactures device_id
				countManufacturer, errCountManufacturer := repo.CountManufacturerBySn(row.Sn)
				if errCountManufacturer != nil {
					w.WriteJSON(map[string]interface{}{"Status": "error", "Message": errCountManufacturer.Error()})
					return
				}
				if countManufacturer > 0 {
					manufacturerId, errGetManufacturerBySn := repo.GetManufacturerIdBySn(row.Sn)
					if errGetManufacturerBySn != nil {
						w.WriteJSON(map[string]interface{}{"Status": "error", "Message": errGetManufacturerBySn.Error()})
						return
					}
					_, errUpdate := repo.UpdateManufacturerDeviceIdById(manufacturerId, device.ID)
					if errUpdate != nil {
						w.WriteJSON(map[string]interface{}{"Status": "error", "Message": errUpdate.Error()})
						return
					}
				}
			}
		}
	}

	//删除文件
	if util.FileExist(file) {
		err := os.Remove(file)
		if err != nil {
			w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
			return
		}
	}
	w.WriteJSON(map[string]interface{}{"Status": "success", "Message": "操作成功"})
}
Exemplo n.º 9
0
func SaveDhcpSubnet(ctx context.Context, w rest.ResponseWriter, r *rest.Request) {
	repo, ok := middleware.RepoFromContext(ctx)
	if !ok {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "内部服务器错误"})
		return
	}
	var info struct {
		ID          uint
		StartIp     string
		EndIp       string
		Gateway     string
		AccessToken string
	}

	if err := r.DecodeJSONPayload(&info); err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "参数错误"})
		return
	}

	info.StartIp = strings.TrimSpace(info.StartIp)
	info.EndIp = strings.TrimSpace(info.EndIp)
	info.Gateway = strings.TrimSpace(info.Gateway)

	isValidate, err := regexp.MatchString("^((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)$", info.StartIp)
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "参数错误" + err.Error()})
		return
	}
	if !isValidate {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "起始IP格式不正确!", "Content": ""})
		return
	}

	isValidateEndIp, err := regexp.MatchString("^((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)$", info.EndIp)
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "参数错误" + err.Error()})
		return
	}
	if !isValidateEndIp {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "结束IP格式不正确!", "Content": ""})
		return
	}

	isValidateGateway, err := regexp.MatchString("^((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)$", info.Gateway)
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "参数错误" + err.Error()})
		return
	}
	if !isValidateGateway {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "网关格式不正确!", "Content": ""})
		return
	}

	info.AccessToken = strings.TrimSpace(info.AccessToken)
	_, errVerify := VerifyAccessPurview(info.AccessToken, ctx, true, w, r)
	if errVerify != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": errVerify.Error()})
		return
	}

	if info.StartIp == "" || info.EndIp == "" || info.Gateway == "" {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "请将信息填写完整!"})
		return
	}

	if info.ID > uint(0) {
		_, err := repo.UpdateDhcpSubnetById(info.ID, info.StartIp, info.EndIp, info.Gateway)
		if err != nil {
			w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
			return
		}
	} else {
		_, err := repo.AddDhcpSubnet(info.StartIp, info.EndIp, info.Gateway)
		if err != nil {
			w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
			return
		}
	}

	logger, ok := middleware.LoggerFromContext(ctx)
	if !ok {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "内部服务器错误"})
		return
	}

	//save to dhcp config file
	file := "/etc/dhcp/dhcpd.conf"
	if !util.FileExist(file) {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "数据已保存,DHCP配置文件(" + file + ")不存在,请手工配置!"})
		return
	}

	text, err := util.ReadFile(file)
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
		return
	}
	reg, err := regexp.Compile("(?s)subnet(\\s+)(.*?)(\\s+)(netmask)(\\s+)(.*?)(\\s+){(.*?)}")
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
		return
	}
	matchs := reg.FindAllStringSubmatch(text, -1)
	if len(matchs) <= 0 {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "DHCP配置文件(" + file + ")未配置subnet节点,请手工操作!"})
		return
	}

	if len(matchs) > 1 {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "DHCP配置文件(" + file + ")存在多个subnet节点,请手工操作!"})
		return
	}

	strFormat := `subnet %s netmask %s {
	range %s %s;
	option routers %s;
}`
	str := fmt.Sprintf(strFormat,
		matchs[0][2],
		matchs[0][6],
		info.StartIp,
		info.EndIp,
		info.Gateway)
	text = strings.Replace(text, matchs[0][0], str, -1)

	logger.Debugf("update dhcp config %s:%s", file, text)
	var bytes = []byte(text)
	errWrite := ioutil.WriteFile(file, bytes, 0666)
	if errWrite != nil {
		logger.Errorf("error:%s", errWrite.Error())
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": errWrite.Error()})
		return
	}

	//restart dhcp service
	var cmd = "service dhcpd restart"
	logger.Debugf("restart dhcpd:%s", cmd)
	restartBytes, err := util.ExecScript(cmd)
	logger.Debugf("result:%s", string(restartBytes))

	var runResult = "<br>执行脚本:" + cmd
	runResult += "<br>" + "执行结果:" + string(restartBytes)

	if err != nil {
		runResult += "<br>" + "错误信息:" + err.Error()
		logger.Errorf("error:%s", err.Error())
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "DHCP重启失败!" + runResult})
		return
	}

	w.WriteJSON(map[string]interface{}{"Status": "success", "Message": "操作成功"})
}