Exemple #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
}
Exemple #2
0
func GetSystemBySn(ctx context.Context, w rest.ResponseWriter, r *rest.Request) {
	var info struct {
		Sn   string
		Type string
	}

	info.Sn = r.FormValue("sn")
	info.Type = r.FormValue("type")
	info.Sn = strings.TrimSpace(info.Sn)
	info.Type = strings.TrimSpace(info.Type)

	if info.Type == "" {
		info.Type = "raw"
	}

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

	if info.Sn == "" {
		if info.Type == "raw" {
			w.Write([]byte(""))
		} else {
			w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "SN参数不能为空"})
		}
		return
	}

	mod, err := repo.GetSystemBySn(info.Sn)
	if err != nil {
		if info.Type == "raw" {
			w.Write([]byte(""))
		} else {
			w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error(), "Content": ""})
		}

		return
	}

	if info.Type == "raw" {
		w.Header().Add("Content-type", "text/html; charset=utf-8")
		w.Write([]byte(mod.Content))
	} else {
		w.WriteJSON(map[string]interface{}{"Status": "success", "Message": "成功获取system信息", "Content": mod})
	}
}
Exemple #3
0
func IsInPreInstallList(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": "内部服务器错误", "Content": ""})
		return
	}
	var info struct {
		Sn string
	}

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

	info.Sn = strings.TrimSpace(info.Sn)

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

	deviceId, err := repo.GetDeviceIdBySn(info.Sn)
	result := make(map[string]string)
	if err != nil {
		result["Result"] = "false"
		w.WriteJSON(map[string]interface{}{"Status": "success", "Message": "该设备不在安装列表里", "Content": result})
		return
	}

	device, err := repo.GetDeviceById(deviceId)
	if err != nil {
		result["Result"] = "false"
		w.WriteJSON(map[string]interface{}{"Status": "success", "Message": "该设备不在安装列表里", "Content": result})
		return
	}

	if device.Status == "pre_install" || device.Status == "installing" {
		result["Result"] = "true"
		w.WriteJSON(map[string]interface{}{"Status": "success", "Message": "该设备在安装列表里", "Content": result})
	} else {
		result["Result"] = "false"
		w.WriteJSON(map[string]interface{}{"Status": "success", "Message": "该设备不在安装列表里", "Content": result})
	}
}
Exemple #4
0
func ExportHardware(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 {
			Ids []int
		}

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

	var where string
	where = " and is_system_add = 'Yes' "
	idsParam := r.FormValue("ids")
	if idsParam != "" {
		ids := strings.Split(idsParam, ",")
		if len(ids) > 0 {
			/*
				for _, id := range info.Ids {
					ids = append(ids, strconv.Itoa(id))
				}
			*/
			where += " and id in (" + strings.Join(ids, ",") + ")"
		}
	}

	company := r.FormValue("company")
	if company != "" {
		where += " and company = '" + company + "' "
	}

	product := r.FormValue("product")
	if product != "" {
		where += " and product = '" + product + "' "
	}

	modelName := r.FormValue("modelName")
	if modelName != "" {
		where += " and model_name = '" + modelName + "' "
	}

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

	var result []map[string]interface{}
	for _, v := range mods {
		result2 := make(map[string]interface{})
		result2["Company"] = v.Company
		result2["Product"] = v.Product
		result2["ModelName"] = v.ModelName
		result2["IsSystemAdd"] = v.IsSystemAdd
		result2["Tpl"] = v.Tpl
		result2["Data"] = v.Data
		result = append(result, result2)
	}

	filename := "idcos-osinstall-hardware.json"
	w.Header().Add("Content-Disposition", fmt.Sprintf("attachment; filename='%s';filename*=utf-8''%s", filename, filename))
	w.Header().Add("Content-Type", "application/octet-stream")
	err = json.NewEncoder(w).Encode(result)
	if err != nil {
		fmt.Println(err)
	}
}
//查询安装信息
func GetDevicePrepareInstallInfo(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
	}

	var info struct {
		Sn        string
		Company   string
		Product   string
		ModelName string
	}

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

	info.Sn = strings.TrimSpace(info.Sn)
	info.Company = strings.TrimSpace(info.Company)
	info.Product = strings.TrimSpace(info.Product)
	info.ModelName = strings.TrimSpace(info.ModelName)

	if info.Sn == "" || info.Company == "" {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "SN及厂商信息不能为空!"})
		return
	}

	result := make(map[string]string)
	//校验是否在配置库
	isValidate, err := repo.ValidateHardwareProductModel(info.Company, info.Product, info.ModelName)
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error(), "Content": result})
		return
	}
	if isValidate == true {
		result["IsVerify"] = "true"
	} else {
		result["IsVerify"] = "false"
	}

	result["IsSkipHardwareConfig"] = "false"
	//是否跳过硬件配置(用户是否配置硬件配置模板)
	if info.Sn != "" {
		count, err := repo.CountDeviceBySn(info.Sn)
		if err != nil {
			w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error(), "Content": result})
			return
		}

		if count > 0 {
			device, err := repo.GetDeviceBySn(info.Sn)
			if err != nil {
				w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error(), "Content": result})
				return
			}
			if device.HardwareID <= uint(0) {
				result["IsSkipHardwareConfig"] = "true"
			}
		}
	}

	w.WriteJSON(map[string]interface{}{"Status": "success", "Message": "操作成功", "Content": result})
}
//上报厂商信息
func ReportProductInfo(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
	}

	type NicInfo struct {
		Name string
		Mac  string
		Ip   string
	}
	type CpuInfo struct {
		Model string
		Core  string
	}
	type DiskInfo struct {
		Name string
		Size string
	}
	type MemoryInfo struct {
		Name string
		Size string
	}
	type MotherboardInfo struct {
		Name  string
		Model string
	}

	var infoFull struct {
		Sn               string
		Company          string
		Product          string
		ModelName        string
		Ip               string
		Mac              string
		Nic              []NicInfo
		Cpu              CpuInfo
		CpuSum           uint
		Memory           []MemoryInfo
		MemorySum        uint
		Disk             []DiskInfo
		DiskSum          uint
		Motherboard      MotherboardInfo
		Raid             string
		Oob              string
		DeviceID         uint
		IsVm             string
		NicDevice        string
		IsShowInScanList string
	}

	var info struct {
		Sn               string
		Company          string
		Product          string
		ModelName        string
		Ip               string
		Mac              string
		Nic              string
		Cpu              string
		CpuSum           uint
		Memory           string
		MemorySum        uint
		Disk             string
		DiskSum          uint
		Motherboard      string
		Raid             string
		Oob              string
		DeviceID         uint
		IsVm             string
		NicDevice        string
		IsShowInScanList string
	}

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

	infoFull.Sn = strings.TrimSpace(infoFull.Sn)
	infoFull.Company = strings.TrimSpace(infoFull.Company)
	infoFull.Product = strings.TrimSpace(infoFull.Product)
	infoFull.ModelName = strings.TrimSpace(infoFull.ModelName)
	infoFull.IsVm = strings.TrimSpace(infoFull.IsVm)
	infoFull.NicDevice = strings.TrimSpace(infoFull.NicDevice)

	info.Sn = infoFull.Sn
	info.Company = infoFull.Company
	info.Product = infoFull.Product
	info.ModelName = infoFull.ModelName
	info.Ip = infoFull.Ip
	info.Mac = infoFull.Mac
	info.Raid = infoFull.Raid
	info.Oob = infoFull.Oob
	info.DeviceID = infoFull.DeviceID
	info.CpuSum = infoFull.CpuSum
	info.MemorySum = infoFull.MemorySum
	info.DiskSum = infoFull.DiskSum
	info.IsVm = infoFull.IsVm
	info.NicDevice = infoFull.NicDevice
	info.IsShowInScanList = "Yes"
	if info.IsVm != "Yes" {
		info.IsVm = "No"
	}

	if infoFull.Cpu.Core != "" {
		core, _ := strconv.Atoi(infoFull.Cpu.Core)
		if core > 0 && info.CpuSum <= uint(0) {
			info.CpuSum = uint(core)
		}
	}
	//nic
	nic, err := json.Marshal(infoFull.Nic)
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
		return
	}
	info.Nic = string(nic)

	//bootos ip
	for _, nicInfo := range infoFull.Nic {
		nicInfo.Ip = strings.TrimSpace(nicInfo.Ip)
		if nicInfo.Ip != "" {
			info.Ip = nicInfo.Ip
			break
		}
	}

	//cpu
	cpu, err := json.Marshal(infoFull.Cpu)
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
		return
	}
	info.Cpu = string(cpu)

	//memory
	memory, err := json.Marshal(infoFull.Memory)
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
		return
	}
	info.Memory = string(memory)

	//disk
	disk, err := json.Marshal(infoFull.Disk)
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
		return
	}
	info.Disk = string(disk)

	//motherboard
	motherboard, err := json.Marshal(infoFull.Motherboard)
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
		return
	}
	info.Motherboard = string(motherboard)

	if info.Sn == "" || info.Company == "" {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "SN和厂商名称不能为空!"})
		return
	}

	countDevice, err := repo.CountDeviceBySn(info.Sn)
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
		return
	}
	if countDevice > 0 {
		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
		}

		info.DeviceID = device.ID
		/*
			count, err := repo.CountManufacturerByDeviceID(device.ID)
			if err != nil {
				w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
				return
			}
		*/

	} else {
		info.DeviceID = uint(0)
	}

	count, err := repo.CountManufacturerBySn(info.Sn)
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
		return
	}
	if count > 0 {
		id, err := repo.GetManufacturerIdBySn(info.Sn)
		if err != nil {
			w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
			return
		}

		_, errUpdate := repo.UpdateManufacturerById(id, info.Company, info.Product, info.ModelName, info.Sn, info.Ip, info.Mac, info.Nic, info.Cpu, info.CpuSum, info.Memory, info.MemorySum, info.Disk, info.DiskSum, info.Motherboard, info.Raid, info.Oob, info.IsVm, info.NicDevice, info.IsShowInScanList)
		if errUpdate != nil {
			w.WriteJSON(map[string]interface{}{"Status": "error", "Message": errUpdate.Error()})
			return
		}

	} else {
		_, err := repo.AddManufacturer(info.DeviceID, info.Company, info.Product, info.ModelName, info.Sn, info.Ip, info.Mac, info.Nic, info.Cpu, info.CpuSum, info.Memory, info.MemorySum, info.Disk, info.DiskSum, info.Motherboard, info.Raid, info.Oob, info.IsVm, info.NicDevice, info.IsShowInScanList)
		if err != nil {
			w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
			return
		}
	}

	w.WriteJSON(map[string]interface{}{"Status": "success", "Message": "操作成功"})
}
func ExportScanDeviceList(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 {
		Keyword    string
		Company    string
		Product    string
		ModelName  string
		CpuRule    string
		Cpu        string
		MemoryRule string
		Memory     string
		DiskRule   string
		Disk       string
		UserID     string
	}

	info.Keyword = r.FormValue("Keyword")
	info.UserID = r.FormValue("UserID")
	info.Company = r.FormValue("Company")
	info.Product = r.FormValue("Product")
	info.ModelName = r.FormValue("ModelName")
	info.CpuRule = r.FormValue("CpuRule")
	info.Cpu = r.FormValue("Cpu")
	info.MemoryRule = r.FormValue("MemoryRule")
	info.Memory = r.FormValue("Memory")
	info.DiskRule = r.FormValue("DiskRule")
	info.Disk = r.FormValue("Disk")

	info.UserID = strings.TrimSpace(info.UserID)
	info.Keyword = strings.TrimSpace(info.Keyword)
	info.Company = strings.TrimSpace(info.Company)
	info.Product = strings.TrimSpace(info.Product)
	info.ModelName = strings.TrimSpace(info.ModelName)
	info.CpuRule = strings.TrimSpace(info.CpuRule)
	info.Cpu = strings.TrimSpace(info.Cpu)
	info.MemoryRule = strings.TrimSpace(info.MemoryRule)
	info.Memory = strings.TrimSpace(info.Memory)
	info.DiskRule = strings.TrimSpace(info.DiskRule)
	info.Disk = strings.TrimSpace(info.Disk)

	var where string
	where = " and t1.is_show_in_scan_list = 'Yes' "

	if info.UserID != "" {
		var userID int
		userID, _ = strconv.Atoi(info.UserID)
		where += " and t1.user_id = '" + fmt.Sprintf("%d", userID) + "'"
	}

	idsParam := r.FormValue("ids")
	if idsParam != "" {
		ids := strings.Split(idsParam, ",")
		if len(ids) > 0 {
			where += " and t1.id in (" + strings.Join(ids, ",") + ")"
		}
	}

	if info.Company != "" {
		where += " and t1.company = '" + info.Company + "'"
	}
	if info.Product != "" {
		where += " and t1.product = '" + info.Product + "'"
	}
	if info.ModelName != "" {
		where += " and t1.model_name = '" + info.ModelName + "'"
	}
	if info.CpuRule != "" && info.Cpu != "" {
		where += " and t1.cpu_sum " + info.CpuRule + info.Cpu
	}
	if info.MemoryRule != "" && info.Memory != "" {
		where += " and t1.memory_sum " + info.MemoryRule + info.Memory
	}
	if info.DiskRule != "" && info.Disk != "" {
		where += " and t1.disk_sum " + info.DiskRule + info.Disk
	}

	if info.Keyword != "" {
		where += " and ( "
		info.Keyword = strings.Replace(info.Keyword, "\n", ",", -1)
		info.Keyword = strings.Replace(info.Keyword, ";", ",", -1)
		list := strings.Split(info.Keyword, ",")
		for k, v := range list {
			var str string
			v = strings.TrimSpace(v)
			if k == 0 {
				str = ""
			} else {
				str = " or "
			}
			where += str + " t1.sn = '" + v + "' or t1.ip = '" + v + "' or t1.company = '" + v + "' or t1.product = '" + v + "' or t1.model_name = '" + v + "'"
		}
		isValidate, _ := regexp.MatchString("^((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)$", info.Keyword)
		if isValidate {
			where += " or t1.nic like '%%\"" + info.Keyword + "\"%%' "
		}
		where += " ) "
	}

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

	var str string
	var strTitle string
	strTitle = "SN(必填),主机名(必填),IP(必填),操作系统(必填),硬件配置模板,系统安装模板(必填),位置(必填),财编,管理IP,是否支持安装虚拟机(Yes或No)\n"
	for _, device := range mods {
		str += device.Sn + ","
		str += ","
		str += ","
		str += ","
		str += ","
		str += ","
		str += ","
		str += ","
		str += ","
		str += "\n"
	}

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

	bytes := []byte(gbkStr + str)

	filename := "idcos-osinstall-scan-device.csv"
	w.Header().Add("Content-Disposition", fmt.Sprintf("attachment; filename='%s';filename*=utf-8''%s", filename, filename))
	w.Header().Add("Content-Type", "application/octet-stream")
	w.Write(bytes)
}
Exemple #8
0
func GetNetworkBySn(ctx context.Context, w rest.ResponseWriter, r *rest.Request) {
	var info struct {
		Sn   string
		Type string
	}

	info.Sn = r.FormValue("sn")
	info.Type = r.FormValue("type")
	info.Sn = strings.TrimSpace(info.Sn)
	info.Type = strings.TrimSpace(info.Type)

	if info.Type == "" {
		info.Type = "raw"
	}

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

	if info.Sn == "" {
		if info.Type == "raw" {
			w.Write([]byte(""))
		} else {
			w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "SN参数不能为空"})
		}
		return
	}

	deviceId, err := repo.GetDeviceIdBySn(info.Sn)
	if err != nil {
		if info.Type == "raw" {
			w.Write([]byte(""))
		} else {
			w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error(), "Content": ""})
		}
		return
	}

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

	mod, err := repo.GetNetworkBySn(info.Sn)
	if err != nil {
		if info.Type == "raw" {
			w.Write([]byte(""))
		} else {
			w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error(), "Content": ""})
		}
		return
	}

	result := make(map[string]interface{})
	result["Hostname"] = device.Hostname
	result["Ip"] = device.Ip
	result["Netmask"] = mod.Netmask
	result["Gateway"] = mod.Gateway
	result["Vlan"] = mod.Vlan
	result["Trunk"] = mod.Trunk
	result["Bonding"] = mod.Bonding
	if info.Type == "raw" {
		w.Header().Add("Content-type", "text/html; charset=utf-8")
		var str string
		if device.Hostname != "" {
			str += "HOSTNAME=\"" + device.Hostname + "\""
		}
		if device.Ip != "" {
			str += "\nIPADDR=\"" + device.Ip + "\""
		}
		if mod.Netmask != "" {
			str += "\nNETMASK=\"" + mod.Netmask + "\""
		}
		if mod.Gateway != "" {
			str += "\nGATEWAY=\"" + mod.Gateway + "\""
		}
		if mod.Vlan != "" {
			str += "\nVLAN=\"" + mod.Vlan + "\""
		}
		if mod.Trunk != "" {
			str += "\nTrunk=\"" + mod.Trunk + "\""
		}
		if mod.Bonding != "" {
			str += "\nBonding=\"" + mod.Bonding + "\""
		}
		w.Write([]byte(str))
	} else {
		w.Header().Add("Content-type", "application/json; charset=utf-8")
		w.WriteJSON(map[string]interface{}{"Status": "success", "Message": "成功获取network信息", "Content": result})
	}
}
Exemple #9
0
func GetHardwareBySn(ctx context.Context, w rest.ResponseWriter, r *rest.Request) {
	w.Header().Add("Content-type", "application/json; charset=utf-8")
	//repo := middleware.RepoFromContext(ctx)
	repo, ok := middleware.RepoFromContext(ctx)
	if !ok {
		//rest.Error(w, " ,", http.StatusInternalServerError)
		//w.WriteHeader(http.StatusFound)
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "内部服务器错误", "Content": ""})
		return
	}
	var info struct {
		Sn string
	}
	if err := r.DecodeJSONPayload(&info); err != nil {
		//rest.Error(w, " ", http.status)
		//w.WriteHeader(http.StatusFound)
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "参数错误", "Content": ""})
		return
	}

	info.Sn = strings.TrimSpace(info.Sn)

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

	hardware, err := repo.GetHardwareBySn(info.Sn)
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error(), "Content": ""})
		return
	}

	type ChildData struct {
		Name  string `json:"Name"`
		Value string `json:"Value"`
	}

	type ScriptData struct {
		Name string       `json:"Name"`
		Data []*ChildData `json:"Data"`
	}

	var data []*ScriptData
	var result2 []map[string]interface{}
	if hardware.Data != "" {
		bytes := []byte(hardware.Data)
		errData := json.Unmarshal(bytes, &data)
		if errData != nil {
			w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error(), "Content": ""})
			return
		}

		for _, v := range data {
			result3 := make(map[string]interface{})
			result3["Name"] = v.Name
			var result5 []map[string]interface{}
			for _, v2 := range v.Data {
				result4 := make(map[string]interface{})
				result4["Name"] = v2.Name
				result4["Script"] = base64.StdEncoding.EncodeToString([]byte(v2.Value))
				result5 = append(result5, result4)
			}
			result3["Scripts"] = result5
			result2 = append(result2, result3)
		}
	}

	result := make(map[string]interface{})
	result["Company"] = hardware.Company
	result["Product"] = hardware.Product
	result["ModelName"] = hardware.ModelName

	/*
		resultHardware := make(map[string]string)
		resultHardware["Raid"] = base64.StdEncoding.EncodeToString([]byte(hardware.Raid))
		resultHardware["Oob"] = base64.StdEncoding.EncodeToString([]byte(hardware.Oob))
		resultHardware["Bios"] = base64.StdEncoding.EncodeToString([]byte(hardware.Bios))
	*/
	result["Hardware"] = result2

	w.WriteJSON(map[string]interface{}{"Status": "success", "Message": "成功获取hardware信息", "Content": result})
}
Exemple #10
0
//上报厂商信息
func ReportProductInfo(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
	}
	var info struct {
		Sn        string
		Company   string
		Product   string
		ModelName string
	}

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

	info.Sn = strings.TrimSpace(info.Sn)
	info.Company = strings.TrimSpace(info.Company)
	info.Product = strings.TrimSpace(info.Product)
	info.ModelName = strings.TrimSpace(info.ModelName)

	if info.Sn == "" || info.Company == "" {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "参数错误!"})
		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
	}

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

	result := make(map[string]string)
	if count > 0 {
		manufacturer, err := repo.GetManufacturerByDeviceID(device.ID)
		if err != nil {
			w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error(), "Content": result})
			return
		}
		_, errUpdate := repo.UpdateManufacturerById(manufacturer.ID, info.Company, info.Product, info.ModelName)
		if errUpdate != nil {
			w.WriteJSON(map[string]interface{}{"Status": "error", "Message": errUpdate.Error(), "Content": result})
			return
		}

	} else {
		_, err := repo.AddManufacturer(device.ID, info.Company, info.Product, info.ModelName)
		if err != nil {
			w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error(), "Content": result})
			return
		}
	}

	//校验是否在配置库
	isValidate, err := repo.ValidateHardwareProductModel(info.Company, info.Product, info.ModelName)
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error(), "Content": result})
		return
	}
	if isValidate == true {
		result["IsVerify"] = "true"
	} else {
		result["IsVerify"] = "false"
	}

	w.WriteJSON(map[string]interface{}{"Status": "success", "Message": "操作成功", "Content": result})
}
Exemple #11
0
//上报Mac信息,生成Pxe文件
func ReportMacInfo(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
		Mac string
	}

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

	info.Sn = strings.TrimSpace(info.Sn)
	info.Mac = strings.TrimSpace(info.Mac)

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

	//mac 大写转为 小写
	info.Mac = strings.ToLower(info.Mac)

	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
	}

	osConfig, err := repo.GetOsConfigById(device.OsID)
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "PXE信息没有配置" + err.Error()})
		return
	}

	//录入Mac信息
	count, err := repo.CountMacByMacAndDeviceID(info.Mac, device.ID)
	if count <= 0 {
		count, err := repo.CountMacByMac(info.Mac)
		if err != nil {
			w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
			return
		}

		if count > 0 {
			w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "该MAC地址已被其他机器录入"})
			return
		}

		_, errAddMac := repo.AddMac(device.ID, info.Mac)
		if errAddMac != nil {
			w.WriteJSON(map[string]interface{}{"Status": "error", "Message": errAddMac.Error()})
			return
		}
	}

	//替换占位符
	osConfig.Pxe = strings.Replace(osConfig.Pxe, "{sn}", info.Sn, -1)

	pxeFileName := util.GetPxeFileNameByMac(info.Mac)
	errCreatePxeFile := util.CreatePxeFile(conf.OsInstall.PxeConfigDir, pxeFileName, osConfig.Pxe)
	if errCreatePxeFile != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "配置文件生成失败" + err.Error()})
		return
	}

	result := make(map[string]string)
	result["Result"] = "true"
	w.WriteJSON(map[string]interface{}{"Status": "success", "Message": "操作成功", "Content": result})
}
Exemple #12
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})
}