torabkheslat 4 years ago
parent
commit
36ff51c8bf
6 changed files with 746 additions and 35 deletions
  1. 117 3
      Billing.go
  2. BIN
      ZiCloud-API
  3. 174 15
      handler.go
  4. 4 3
      main.go
  5. 450 13
      ovirt.go
  6. 1 1
      token.go

+ 117 - 3
Billing.go

@@ -198,6 +198,36 @@ func (b billing) Show(c echo.Context) error {
 	client := &http.Client{}
 	req, err := http.NewRequest(method, url, nil)
 
+	if InvoiceUUID == "556a5032-09de-4430-b1e1-48a2ef84d62f" {
+		_Invoice := Invoice{
+			CreatedAt:       time.Time{},
+			UpdatedAt:       time.Time{},
+			ID:              0,
+			UUID:            UserUUID,
+			CustomerID:      "xxx",
+			Plan:            "12",
+			DurationDay:     100,
+			VcoreQuantity:   100,
+			VcoreCost:       100,
+			RAMQuantity:     100,
+			RAMCost:         100,
+			StorageQuantity: 100,
+			StorageCost:     100,
+			ExtraIPCount:    100,
+			ExtraIPCost:     100,
+			ExtraBwQuantity: 100,
+			ExtraBwCost:     100,
+			Sum:             100,
+		}
+		fake_InvoiceResponse := InvoiceResponse{
+			Data:    _Invoice,
+			Message: "Done",
+			Origin:  "Billing-ShowInvoice",
+			Code:    1000,
+		}
+		return c.JSON(http.StatusOK, fake_InvoiceResponse)
+	}
+
 	if err != nil {
 		fmt.Println(err)
 		return nil
@@ -267,7 +297,6 @@ func IaaSCreate(UserUUID string, period string, CPU string, memory string, stora
 	_storageVolume, _ := strconv.Atoi(storageVolume)
 	_extraIP, _ := strconv.Atoi(extraIP)
 	_extraBW, _ := strconv.Atoi(extraBW)
-	///TODO: fix static items
 	payload := strings.NewReader(fmt.Sprintf(`{
     "customerId": "%s",
     "durationDay": "%d",
@@ -276,8 +305,8 @@ func IaaSCreate(UserUUID string, period string, CPU string, memory string, stora
     "storageVolume": "%d",
     "extraIPCount": "%d",
     "extraBW": "%d",
-	"isTransient":"%t",
-	"coupon":"%d"
+	  "isTransient": %t,
+		"coupon":"%d"
 }`, UserUUID, _period*30, _CPU, _memory/1024/1024/1024, _storageVolume/1024/1024/1024, _extraIP, _extraBW, isTransient, coupon))
 	//}`, UserUUID, _period*30, _CPU, _memory/1024/1024/1024, _storageVolume/1024/1024/1024, _extraIP, _extraBW))
 	//fmt.Println("Mem1 :",memory," Mem2:",_memory,"Array: ",payload)
@@ -317,3 +346,88 @@ func IaaSCreate(UserUUID string, period string, CPU string, memory string, stora
 	StoragePrice = _CreateResponse.StorageCost
 	return CPUPrice, memPrice, StoragePrice, IPPrice, extraBWPrice, _CreateResponse.Sum, _CreateResponse.SumRaw, _CreateResponse.UUID
 }
+func IaaSEdit(UserUUID string, period string, CPU string, memory string, storageVolume string, extraIP string, extraBW string, isTransient bool, coupon int, vmUUID string) (CPUPrice float64, memPrice float64, StoragePrice float64, IPPrice float64, extraBWPrice float64, sum float64, sumRaw float64, InvoiceID string) {
+	type EditResponse struct {
+		CreatedAt       time.Time `json:"createdAt"`
+		UpdatedAt       time.Time `json:"updatedAt"`
+		ID              int       `json:"id"`
+		UUID            string    `json:"uuid"`
+		CustomerID      string    `json:"customerId"`
+		Plan            string    `json:"plan"`
+		DurationDay     int       `json:"durationDay"`
+		VcoreQuantity   int       `json:"vcoreQuantity"`
+		VcoreCost       float64   `json:"vcoreCost"`
+		RAMQuantity     int       `json:"ramQuantity"`
+		RAMCost         float64   `json:"ramCost"`
+		StorageQuantity int       `json:"storageQuantity"`
+		StorageCost     float64   `json:"storageCost"`
+		ExtraIPCount    int       `json:"extraIpCount"`
+		ExtraIPCost     float64   `json:"extraIpCost"`
+		ExtraBwQuantity int       `json:"extraBwQuantity"`
+		ExtraBwCost     float64   `json:"extraBwCost"`
+		Sum             float64   `json:"sum"`
+		SumRaw          float64   `json:"SumRaw"`
+	}
+	url := "http://172.20.15.24:80/invoice/iaas/edit"
+	method := "POST"
+	_period, _ := strconv.Atoi(period)
+	_CPU, _ := strconv.Atoi(CPU)
+	_memory, _ := strconv.Atoi(memory)
+	_storageVolume, _ := strconv.Atoi(storageVolume)
+	_extraIP, _ := strconv.Atoi(extraIP)
+	_extraBW, _ := strconv.Atoi(extraBW)
+	payload := strings.NewReader(fmt.Sprintf(`{
+  "customerId": "%s",
+  "newRequest": {
+    "coupon": "%d",
+    "customerId": "%s",
+    "durationDay": "%d",
+    "extraBW": "%d",
+    "extraIPCount": "%d",
+    "isTransient": %t,
+    "previousRemainingCredit": 0,
+    "ramVolume": "%d",
+    "storageVolume": "%d",
+    "vCoreCount": "%d" 
+  },
+  "serviceUUID": "%s"
+}`, UserUUID, coupon, UserUUID, _period*30, _extraBW, _extraIP, isTransient, _memory/1024/1024/1024, _storageVolume/1024/1024/1024, _CPU, vmUUID))
+	//}`, UserUUID, _period*30, _CPU, _memory/1024/1024/1024, _storageVolume/1024/1024/1024, _extraIP, _extraBW))
+	//fmt.Println("Mem1 :",memory," Mem2:",_memory,"Array: ",payload)
+	client := &http.Client{}
+	req, err := http.NewRequest(method, url, payload)
+
+	if err != nil {
+		fmt.Println(err)
+		return CPUPrice, memPrice, StoragePrice, IPPrice, extraBWPrice, sum, sumRaw, InvoiceID
+	}
+	req.Header.Add("Content-Type", "application/json")
+
+	res, err := client.Do(req)
+	if err != nil {
+		fmt.Println(err)
+		return CPUPrice, memPrice, StoragePrice, IPPrice, extraBWPrice, sum, sumRaw, InvoiceID
+	}
+	defer res.Body.Close()
+
+	body, err := ioutil.ReadAll(res.Body)
+	if err != nil {
+		fmt.Println(err)
+		return CPUPrice, memPrice, StoragePrice, IPPrice, extraBWPrice, sum, sumRaw, InvoiceID
+	}
+	//fmt.Println(string(body))
+	//return CPUPrice, memPrice, StoragePrice, IPPrice, extraBWPrice
+	_EditResponse := EditResponse{}
+	err = json.Unmarshal(body, &_EditResponse)
+	if err != nil {
+		fmt.Println(err)
+		//return CPUPrice, memPrice, StoragePrice, IPPrice, extraBWPrice
+	}
+	CPUPrice = _EditResponse.VcoreCost
+	memPrice = _EditResponse.RAMCost
+	extraBWPrice = _EditResponse.ExtraBwCost
+	IPPrice = _EditResponse.ExtraIPCost
+	StoragePrice = _EditResponse.StorageCost
+	fmt.Println(CPUPrice, memPrice, StoragePrice, IPPrice, extraBWPrice, _EditResponse.Sum, _EditResponse.SumRaw, _EditResponse.UUID)
+	return CPUPrice, memPrice, StoragePrice, IPPrice, extraBWPrice, _EditResponse.Sum, _EditResponse.SumRaw, _EditResponse.UUID
+}

BIN
ZiCloud-API


+ 174 - 15
handler.go

@@ -497,6 +497,48 @@ func (h *handler) disableUser(c echo.Context) error {
 	//return c.String(http.StatusOK, string(b))
 }
 func (h *handler) resetUser(c echo.Context) error {
+	type ResetResponseErr struct {
+		Result interface{} `json:"result"`
+		Error  struct {
+			Code    int    `json:"code"`
+			Message string `json:"message"`
+			Data    struct {
+				Desc string `json:"desc"`
+				Info string `json:"info"`
+			} `json:"data"`
+			Name string `json:"name"`
+		} `json:"error"`
+		ID        int    `json:"id"`
+		Principal string `json:"principal"`
+		Version   string `json:"version"`
+	}
+	type ResetResponse struct {
+		Result struct {
+			Result struct {
+				Mail             []string `json:"mail"`
+				UID              []string `json:"uid"`
+				Loginshell       []string `json:"loginshell"`
+				Sn               []string `json:"sn"`
+				Givenname        []string `json:"givenname"`
+				Uidnumber        []string `json:"uidnumber"`
+				Krbcanonicalname []string `json:"krbcanonicalname"`
+				Gidnumber        []string `json:"gidnumber"`
+				Homedirectory    []string `json:"homedirectory"`
+				Telephonenumber  []string `json:"telephonenumber"`
+				Krbprincipalname []string `json:"krbprincipalname"`
+				Nsaccountlock    bool     `json:"nsaccountlock"`
+				HasPassword      bool     `json:"has_password"`
+				HasKeytab        bool     `json:"has_keytab"`
+				MemberofGroup    []string `json:"memberof_group"`
+			} `json:"result"`
+			Value   string `json:"value"`
+			Summary string `json:"summary"`
+		} `json:"result"`
+		Error     interface{} `json:"error"`
+		ID        int         `json:"id"`
+		Principal string      `json:"principal"`
+		Version   string      `json:"version"`
+	}
 	type keyJson struct {
 		IPAToken string   `json:"IPAToken"`
 		Admin    bool     `json:"admin"`
@@ -565,10 +607,36 @@ func (h *handler) resetUser(c echo.Context) error {
 	req.Header.Add("Accept", "text/plain")
 	req.Header.Add("Cookie", token)
 	res, err := client.Do(req)
-	//fmt.Println(token)
-	//fmt.Println(_json)
-	//fmt.Println(req)
-	//fmt.Println(res)
+	fmt.Println(token)
+	fmt.Println(_json)
+	fmt.Println(req)
+	fmt.Println(res)
+	//body, err := ioutil.ReadAll(res.Body)
+	//result := ResetResponse{}
+	//resultErr := ResetResponseErr{}
+	//_err := json.Unmarshal(body, &result)
+	//fmt.Println("Sassan:", result.Error)
+	//fmt.Println("SassanType:", reflect.TypeOf(result.Error))
+	//var respErr interface{}
+	//respErrRaw := fmt.Sprintf("%v", result.Error)
+	//fmt.Println(respErrRaw)
+	//json.Unmarshal([]byte(respErrRaw), &respErr)
+	//fmt.Println("Sassan Code:", respErr.(interface{}).(map[string]interface{})["code"])
+	//if _err != nil {
+	//	_err := json.Unmarshal(body, &resultErr)
+	//	resp := _response{
+	//		Origin:  "resetUser",
+	//		Message: "Something went wrong; " + _err.Error() + ": " + resultErr.Error.Message,
+	//		Code:    1001,
+	//	}
+	//	if _err != nil {
+	//		resp.Message = "Something went wrong"
+	//	}
+	//	fmt.Println("Sassan Err:", resp.Message)
+	//	return c.JSON(http.StatusBadRequest, resp)
+	//}
+	//fmt.Println(body)
+	//fmt.Println(string(body))
 	_json = fmt.Sprintf(`
 {
     "id": 0,
@@ -596,9 +664,12 @@ func (h *handler) resetUser(c echo.Context) error {
 	err = nil
 	res, err = client.Do(req)
 	//fmt.Println(token)
-	//fmt.Println(_json)
-	//fmt.Println(req)
-	//fmt.Println(res)
+	// fmt.Println(_json)
+	// fmt.Println(req)
+	// body, err := ioutil.ReadAll(res.Body)
+	// fmt.Println(body)
+	// fmt.Println(string(body))
+
 	if err != nil {
 		//return c.String(http.StatusBadRequest, "Error"+err.Error())
 		return c.JSON(http.StatusBadRequest, "Error"+err.Error())
@@ -844,8 +915,8 @@ func (h *handler) forgetpassword(c echo.Context) error {
 	req.Header.Add("Accept", "text/plain")
 	req.Header.Add("Cookie", token)
 	res, err := client.Do(req)
-	defer res.Body.Close()
 	body, err := ioutil.ReadAll(res.Body)
+	defer res.Body.Close()
 	//fmt.Println("Getting Data for Response: ", body)
 	_user := user_findResult{}
 	json.Unmarshal(body, &_user)
@@ -1076,11 +1147,6 @@ func (h *handler) ListServices(c echo.Context) error {
 }
 func (h *handler) PriceCalc(c echo.Context) error {
 	user := c.Get("user").(*jwt.Token)
-	//db, _ := sql.Open("mysql", MySQLUSER+":"+MySQLPASS+"@tcp(127.0.0.1:3306)/zicloud")
-	//_, _ = db.Query("SELECT uuid as UUID ,task_apiCall as TaskAPICall , cron_expression as CronExpression , related_uuid as Ruuid, type FROM scheduler where active=1")
-	//_, _ = db.Query("SELECT uuid as UUID ,task_apiCall as TaskAPICall , cron_expression as CronExpression , related_uuid as Ruuid, type FROM scheduler where active=1")
-	//_, _ = db.Query("SELECT uuid as UUID ,task_apiCall as TaskAPICall , cron_expression as CronExpression , related_uuid as Ruuid, type FROM scheduler where active=1")
-	//db.Close()
 
 	claims := user.Claims.(jwt.MapClaims)
 	_sha256 := sha256.Sum256([]byte(string(claims["name"].(string))))
@@ -1098,6 +1164,33 @@ func (h *handler) PriceCalc(c echo.Context) error {
 	nic = c.FormValue("VmNIC")
 	extraBW := c.FormValue("extraBW")
 	coupon, _ := strconv.Atoi(c.FormValue("coupon"))
+
+	__cpu, _ := strconv.Atoi(cpu)
+	__mem, _ := strconv.Atoi(mem)
+	__Disk, _ := strconv.Atoi(Disk)
+	__nic, _ := strconv.Atoi(nic)
+	__period, _ := strconv.Atoi(period)
+	__extraBW, _ := strconv.Atoi(extraBW)
+
+	if __cpu < 0 {
+		cpu = "0"
+	}
+	if __mem < 0 {
+		mem = "0"
+	}
+	if __Disk < 0 {
+		Disk = "0"
+	}
+	if __nic < 0 {
+		nic = "0"
+	}
+	if __extraBW < 0 {
+		extraBW = "0"
+	}
+	if __period < 0 {
+		period = "0"
+	}
+
 	type PriceCalculator struct {
 		Data struct {
 			TotalPrice string `json:"TotalPrice"`
@@ -1105,7 +1198,7 @@ func (h *handler) PriceCalc(c echo.Context) error {
 		Origin string `json:"origin"`
 		Code   int    `json:"code"`
 	}
-	_, _, _, _, _, SUM, _, _ := IaaSCreate(login(BA).AuthenticatedUser.ID, period, cpu, mem, Disk, nic, extraBW, false, coupon)
+	_, _, _, _, _, SUM, _, _ := IaaSCreate(login(BA).AuthenticatedUser.ID, period, cpu, mem, Disk, nic, extraBW, true, coupon)
 
 	resp := PriceCalculator{
 		Data: struct {
@@ -1116,6 +1209,71 @@ func (h *handler) PriceCalc(c echo.Context) error {
 	}
 	return c.JSON(http.StatusOK, resp)
 }
+func (h *handler) EditIaaSPriceCalc(c echo.Context) error {
+	user := c.Get("user").(*jwt.Token)
+
+	claims := user.Claims.(jwt.MapClaims)
+	_sha256 := sha256.Sum256([]byte(string(claims["name"].(string))))
+	var hashChannel_ = make(chan []byte, 1)
+	hashChannel_ <- _sha256[:]
+	token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
+	_BA := strings.Split(token, ";")
+	BA := _BA[len(_BA)-2]
+	//token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
+	cpu := c.FormValue("cpu")
+	mem := c.FormValue("mem")
+	Disk := c.FormValue("hdd")
+	nic := c.FormValue("nic")
+	period := c.FormValue("period")
+	nic = c.FormValue("VmNIC")
+	extraBW := c.FormValue("extraBW")
+	VMUUID := c.FormValue("VMUUID")
+	coupon, _ := strconv.Atoi(c.FormValue("coupon"))
+
+	__cpu, _ := strconv.Atoi(cpu)
+	__mem, _ := strconv.Atoi(mem)
+	__Disk, _ := strconv.Atoi(Disk)
+	__nic, _ := strconv.Atoi(nic)
+	__period, _ := strconv.Atoi(period)
+	__extraBW, _ := strconv.Atoi(extraBW)
+
+	if __cpu < 0 {
+		cpu = "0"
+	}
+	if __mem < 0 {
+		mem = "0"
+	}
+	if __Disk < 0 {
+		Disk = "0"
+	}
+	if __nic < 0 {
+		nic = "0"
+	}
+	if __extraBW < 0 {
+		extraBW = "0"
+	}
+	if __period < 0 {
+		period = "0"
+	}
+
+	type PriceCalculator struct {
+		Data struct {
+			TotalPrice string `json:"TotalPrice"`
+		} `json:"message"`
+		Origin string `json:"origin"`
+		Code   int    `json:"code"`
+	}
+	_, _, _, _, _, SUM, _, _ := IaaSEdit(login(BA).AuthenticatedUser.ID, period, cpu, mem, Disk, nic, extraBW, true, coupon, VMUUID)
+
+	resp := PriceCalculator{
+		Data: struct {
+			TotalPrice string `json:"TotalPrice"`
+		}{TotalPrice: strconv.Itoa(int(SUM))},
+		Origin: "EditIaaSPriceCalc",
+		Code:   1000,
+	}
+	return c.JSON(http.StatusOK, resp)
+}
 func (h *handler) showUser(c echo.Context) error {
 
 	type response struct {
@@ -1243,6 +1401,7 @@ func (h *handler) editUser(c echo.Context) error {
 	method := "POST"
 	_json := fmt.Sprintf(`
 {
+	
     "id": 0,
     "method": "user_mod/1",
     "params": [
@@ -1284,8 +1443,8 @@ func (h *handler) editUser(c echo.Context) error {
 	req.Header.Add("Accept", "text/plain")
 	req.Header.Add("Cookie", token)
 	res, err := client.Do(req)
-	defer res.Body.Close()
 	body, err := ioutil.ReadAll(res.Body)
+	defer res.Body.Close()
 	result := editUser{}
 	_err := json.Unmarshal(body, &result)
 	if _err != nil {

+ 4 - 3
main.go

@@ -28,6 +28,7 @@ import (
 var _appversion string = "0.1"
 var _appname string = "ZiCloud-API"
 var URL string = "https://ipa-cl.zi-tel.com"
+
 var OvirtURL string = "https://ovirt-cl.zi-tel.com"
 var RealIP string
 var secretKey = []byte("P*%!5+u!$y+cgM+P8bybzgnXpsd2Lv2z") // 32 bytes
@@ -149,7 +150,6 @@ func main() {
 	h := &handler{}
 	echoHandler.POST("/login", h.login)
 	echoHandler.POST("/uuidgen", h.uuidgen)
-
 	//echoHandler.GET("/admin", h.uuidgen, isLoggedIn, isAdmin)
 	echoHandler.POST("/addUser", h.addUser, isLoggedIn, isAdmin)
 	echoHandler.POST("/editUser", h.editUser, isLoggedIn, isAdmin)
@@ -162,6 +162,7 @@ func main() {
 	echoHandler.POST("/token", h.token, isLoggedIn)
 	echoHandler.POST("/ListServices", h.ListServices, isLoggedIn)
 	echoHandler.POST("/PriceCalc", h.PriceCalc, isLoggedIn)
+	echoHandler.POST("/EditIaaSPriceCalc", h.EditIaaSPriceCalc, isLoggedIn)
 
 	iaas := &ovirt{}
 	echoHandler.GET("/ovirtListVMs", iaas.listVM, isLoggedIn)
@@ -322,7 +323,7 @@ func toggleTask(uuid string, active int) {
 	db, err := sql.Open("mysql", MySQLUSER+":"+MySQLPASS+"@tcp(127.0.0.1:3306)/zicloud")
 	if err != nil {
 	}
-	update, err := db.Query("update scheduler set active='" + fmt.Sprintf("%s", active) + "' where uuid='" + uuid + "'")
+	update, err := db.Query("update scheduler set active='" + fmt.Sprintf("%d", active) + "' where uuid='" + uuid + "'")
 	defer db.Close()
 	if err != nil {
 	}
@@ -345,8 +346,8 @@ func runAPICall(apiCall addVMTask) []byte {
 		fmt.Println(err)
 	}
 	res, err := client.Do(req)
-	defer res.Body.Close()
 	body, _ := ioutil.ReadAll(res.Body)
+	defer res.Body.Close()
 	return body
 }
 func VMPowerMng(relatedUuid string, apiCall string, uuid string) {

+ 450 - 13
ovirt.go

@@ -1285,15 +1285,398 @@ func (o ovirt) AddDisk(c echo.Context) error {
 	return c.JSON(http.StatusOK, resp)
 }
 func (o ovirt) EditVM(c echo.Context) error {
-	resp := _response{
-		Origin:  "ovirt-EditVM",
+	type VMDescr struct {
+		VMName  string `json:"vmname"`
+		VMCpu   string `json:"vmCpu"`
+		VMMem   string `json:"vmMem"`
+		VMNIC   string `json:"vmnic"`
+		VMBW    string `json:"vmbw"`
+		VMUUID  string `json:"vmuuid"`
+		Invoice string `json:"invoice"`
+	}
+	type EditVMPayment struct {
+		Data struct {
+			Price struct {
+				CPU    float64 `json:"cpu"`
+				Mem    float64 `json:"mem"`
+				Disk   float64 `json:"disk"`
+				Nic    float64 `json:"nic"`
+				BW     float64 `json:"bw"`
+				SUM    float64 `json:"sum"`
+				SUMRaw float64 `json:"SUMRaw"`
+				Period string  `json:"period"`
+			} `json:"price"`
+			InvoiceUUID string `json:"invoiceUUID"`
+		} `json:"data"`
+		Message string `json:"message"`
+		Origin  string `json:"origin"`
+		Code    int    `json:"code"`
+	}
+	user := c.Get("user").(*jwt.Token)
+	claims := user.Claims.(jwt.MapClaims)
+	_sha256 := sha256.Sum256([]byte(string(claims["name"].(string))))
+	var hashChannel_ = make(chan []byte, 1)
+	hashChannel_ <- _sha256[:]
+	token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
+	_BA := strings.Split(token, ";")
+	BA := _BA[len(_BA)-2]
+	var vmname, vmuuid, vmdescr, vmcomment, templatename, cpuSock, cpuCore, cpuThread, mem, Disk, nic, period, extraBW string
+	coupon := 0
+	vmname = login(BA).AuthenticatedUser.ID + "-_-" + c.FormValue("VmName")
+	vmdescr = c.FormValue("VmDescr")
+	vmcomment = c.FormValue("VmComment")
+	templatename = c.FormValue("VmTempl")
+	cpuThread = c.FormValue("VmCPU")
+	Disk = c.FormValue("VmDisk")
+	period = c.FormValue("VmPeriod")
+	nic = c.FormValue("VmNIC")
+	extraBW = c.FormValue("extraBW")
+	vmuuid = c.FormValue("VMUUID")
+	// sshKey := c.FormValue("sshKey")
+	// rootpass := c.FormValue("rootpass")
+	coupon, _ = strconv.Atoi(c.FormValue("coupon"))
+	cpuCore = "1"
+	cpuSock = "1"
+	mem = c.FormValue("VmMem")
+	url := OvirtURL + "/ovirt-engine/api/vms"
+	method := "POST"
+	//addvmresponse := AddVMResponse{}O
+	editvm := AddVMRequest{
+		URL: url,
+		JSON: struct {
+			Name        string `json:"name"`
+			Description string `json:"description"`
+			Comment     string `json:"comment"`
+			Cluster     struct {
+				Name string `json:"name"`
+			} `json:"cluster"`
+			Template struct {
+				Name string `json:"name"`
+			} `json:"template"`
+			CPU struct {
+				Topology struct {
+					Sockets string `json:"sockets"`
+					Cores   string `json:"cores"`
+					Threads string `json:"threads"`
+				} `json:"topology"`
+			} `json:"cpu"`
+			Memory       string `json:"memory"`
+			MemoryPolicy struct {
+				Ballooning string `json:"ballooning"`
+				Guaranteed string `json:"guaranteed"`
+				OverCommit struct {
+					Percent string `json:"percent"`
+				} `json:"over_commit"`
+			} `json:"memory_policy"`
+		}{
+			Name:        vmname,
+			Description: vmdescr,
+			Comment:     vmcomment,
+			Cluster: struct {
+				Name string `json:"name"`
+			}{Name: "Default"},
+			Template: struct {
+				Name string `json:"name"`
+			}{Name: templatename},
+			CPU: struct {
+				Topology struct {
+					Sockets string `json:"sockets"`
+					Cores   string `json:"cores"`
+					Threads string `json:"threads"`
+				} `json:"topology"`
+			}{
+				struct {
+					Sockets string `json:"sockets"`
+					Cores   string `json:"cores"`
+					Threads string `json:"threads"`
+				}{
+					Sockets: cpuSock,
+					Cores:   cpuCore,
+					Threads: cpuThread,
+				},
+			},
+			Memory: mem,
+			MemoryPolicy: struct {
+				Ballooning string `json:"ballooning"`
+				Guaranteed string `json:"guaranteed"`
+				OverCommit struct {
+					Percent string `json:"percent"`
+				} `json:"over_commit"`
+			}{
+				Ballooning: "true",
+				Guaranteed: mem,
+				OverCommit: struct {
+					Percent string `json:"percent"`
+				}{Percent: "10"},
+			},
+		},
+		Method:  method,
+		Headers: nil,
+	}
+	editvm.Headers = append(editvm.Headers, struct {
+		Name  string `json:"Name"`
+		Value string `json:"Value"`
+	}{
+		Name:  "Accept",
+		Value: "application/json",
+	})
+	editvm.Headers = append(editvm.Headers, struct {
+		Name  string `json:"Name"`
+		Value string `json:"Value"`
+	}{
+		Name:  "Authorization",
+		Value: BA,
+	})
+	editvm.Headers = append(editvm.Headers, struct {
+		Name  string `json:"Name"`
+		Value string `json:"Value"`
+	}{
+		Name:  "Content-Type",
+		Value: "application/json",
+	})
+	// uuid, _ := uuidgen("APIGW-Ovirt-addVMTask")
+	//invoiceUUID, _ := uuidgen("APIGW-FakeInvoice")
+	CPUPrice, memPrice, StoragePrice, IPPrice, extraBWPrice, SUM, SUMRaw, invoiceUUID := IaaSEdit(login(BA).AuthenticatedUser.ID, period, cpuThread, mem, Disk, nic, extraBW, false, coupon, vmuuid)
+
+	type JSONDetails struct {
+		Name  string `json:"name"`
+		Value string `json:"value"`
+		Type  string `json:"type"`
+	}
+	/*_jsonDetail := [8]JSONDetails{}
+	{
+		_jsonDetail[0].Name = "Period"
+		_jsonDetail[0].Value = period
+		_jsonDetail[0].Type = "int"
+		_jsonDetail[1].Name = "cpuThread"
+		_jsonDetail[1].Value = cpuThread
+		_jsonDetail[1].Type = "int"
+		_jsonDetail[2].Name = "mem"
+		_jsonDetail[2].Value = mem
+		_jsonDetail[2].Type = "int"
+		_jsonDetail[3].Name = "Disk"
+		_jsonDetail[3].Value = Disk
+		_jsonDetail[3].Type = "int"
+		_jsonDetail[4].Name = "nic"
+		_jsonDetail[4].Value = nic
+		_jsonDetail[4].Type = "int"
+		_jsonDetail[5].Name = "extraBW"
+		_jsonDetail[5].Value = extraBW
+		_jsonDetail[5].Type = "int"
+		_jsonDetail[6].Name = "coupon"
+		_jsonDetail[6].Value = fmt.Sprintf("%d", coupon)
+		_jsonDetail[6].Type = "int"
+		_jsonDetail[7].Name = "Template"
+		_jsonDetail[7].Value = templatename
+		_jsonDetail[7].Type = "string"
+	}
+	 jsonDetail, _ := json.Marshal(_jsonDetail)
+	*/
+
+	responseInvoiece := EditVMPayment{
+		Data: struct {
+			Price struct {
+				CPU    float64 `json:"cpu"`
+				Mem    float64 `json:"mem"`
+				Disk   float64 `json:"disk"`
+				Nic    float64 `json:"nic"`
+				BW     float64 `json:"bw"`
+				SUM    float64 `json:"sum"`
+				SUMRaw float64 `json:"SUMRaw"`
+				Period string  `json:"period"`
+			} `json:"price"`
+			InvoiceUUID string `json:"invoiceUUID"`
+		}{
+			Price: struct {
+				CPU    float64 `json:"cpu"`
+				Mem    float64 `json:"mem"`
+				Disk   float64 `json:"disk"`
+				Nic    float64 `json:"nic"`
+				BW     float64 `json:"bw"`
+				SUM    float64 `json:"sum"`
+				SUMRaw float64 `json:"SUMRaw"`
+				Period string  `json:"period"`
+			}{
+				CPU:    CPUPrice,
+				Mem:    memPrice,
+				Disk:   StoragePrice,
+				Nic:    IPPrice,
+				BW:     extraBWPrice,
+				SUM:    SUM,
+				SUMRaw: SUMRaw,
+				Period: period,
+			},
+			InvoiceUUID: invoiceUUID,
+		},
 		Message: "Done",
+		Origin:  "EditVM",
 		Code:    1000,
 	}
-	//b, _ := json.MarshalIndent(resp, "", "  ")
-	//return c.String(http.StatusOK, string(b))
-	return c.JSON(http.StatusOK, resp)
+	responseInvoiece_fake := EditVMPayment{
+		Data: struct {
+			Price struct {
+				CPU    float64 `json:"cpu"`
+				Mem    float64 `json:"mem"`
+				Disk   float64 `json:"disk"`
+				Nic    float64 `json:"nic"`
+				BW     float64 `json:"bw"`
+				SUM    float64 `json:"sum"`
+				SUMRaw float64 `json:"SUMRaw"`
+				Period string  `json:"period"`
+			} `json:"price"`
+			InvoiceUUID string `json:"invoiceUUID"`
+		}{
+			Price: struct {
+				CPU    float64 `json:"cpu"`
+				Mem    float64 `json:"mem"`
+				Disk   float64 `json:"disk"`
+				Nic    float64 `json:"nic"`
+				BW     float64 `json:"bw"`
+				SUM    float64 `json:"sum"`
+				SUMRaw float64 `json:"SUMRaw"`
+				Period string  `json:"period"`
+			}{
+				CPU:    100,
+				Mem:    100,
+				Disk:   100,
+				Nic:    100,
+				BW:     100,
+				SUM:    100,
+				SUMRaw: 100,
+				Period: "12",
+			},
+			InvoiceUUID: "556a5032-09de-4430-b1e1-48a2ef84d62f",
+		},
+		Message: "Done",
+		Origin:  "EditVM",
+		Code:    1000,
+	}
+	// if len(invoiceUUID) < 5 {
+	// 	resp := _response{
+	// 		Origin:  "ovirt-editvm",
+	// 		Message: "Error on Invoice Calculation",
+	// 		Code:    1001,
+	// 	}
+	// 	b, _ := json.MarshalIndent(resp, "", "  ")
+	// 	return c.String(http.StatusBadRequest, string(b))
+	// }
+	fmt.Println("EditVM: ", editvm)
+	fmt.Print(responseInvoiece)
+	return c.JSON(http.StatusOK, responseInvoiece_fake)
+	// return c.JSON(http.StatusOK, fakeResponse)
+	// __createVM, _ := json.MarshalIndent(editvm, "", "  ")
+	// Add VM Task
+	//	addTask(uuid, string(__createVM), "", "APIGW", "VM Creation for "+claims["name"].(string), invoiceUUID, "0", "0")
+
+	/*
+
+			{
+				db, err := sql.Open("mysql", MySQLUSER+":"+MySQLPASS+"@tcp(127.0.0.1:3306)/zicloud")
+				if err != nil {
+					resp := _response{
+						Origin:  "ovirt-Editvm",
+						Message: "Error on connecting db for save add vm result",
+						Code:    1001,
+					}
+					b, _ := json.MarshalIndent(resp, "", "  ")
+					return c.String(http.StatusBadRequest, string(b))
+				}
+				defer db.Close()
+				insert, err := db.Query("INSERT INTO service_profile VALUES ( '" + invoiceUUID + "'," +
+					"'" + claims["IPAUid"].(string) + "'," +
+					"'" + "VM" + "'," +
+					"'" + "" + "'," +
+					"'" + login(BA).AuthenticatedUser.ID + "'," +
+					"NOW()" + "," +
+					"NOW() ," +
+					"-1" + "," +
+					"'" + vmname + "'," +
+					"'" + string(jsonDetail) + "'," +
+					"'" + invoiceUUID + "' )")
+				defer insert.Close()
+				if err != nil {
+					fmt.Println("Error in EditVM: ", err.Error())
+				}
+
+			}
+
+			// Start Task
+			{
+
+				url := OvirtURL + "/ovirt-engine/api/vms/" + invoiceUUID + "/start"
+				method := "POST"
+				nicAddress := "172.20.15.251"
+				nicMask := "255.255.255.0"
+				nicGW := "172.20.15.1"
+				__json := fmt.Sprintf(`
+		{
+			"async":"true",
+		    "use_cloud_init": "true",
+		    "vm": {
+		        "initialization": {
+		            "authorized_ssh_keys": "%s",
+		            "host_name": "Sassan.local",
+		            "user_name": "root",
+		            "root_password": "%s",
+		            "nic_configurations": {
+		                "nic_configuration": [
+		                    {
+		                        "name": "eth0",
+		                        "on_boot": "true",
+		                        "boot_protocol": "static",
+		                        "ip": {
+		                            "address": "%s",
+		                            "netmask": "%s",
+		                            "gateway": "%s"
+		                        }
+		                    }
+		                ]
+		            },
+		            "dns_servers": "172.20.11.11"
+		        }
+		    }
+		}
+		`, sshKey, rootpass, nicAddress, nicMask, nicGW)
+				sha256 := sha256.Sum256([]byte(invoiceUUID))
+				var hashChannel = make(chan []byte, 1)
+				hashChannel <- sha256[:]
+				___json := encrypt(<-hashChannel, __json)
+				startVM := addVMTask{
+					URL:     url,
+					JSON:    ___json,
+					Method:  method,
+					Headers: nil,
+				}
+				startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Version", Value: "4"})
+				startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Accept", Value: "application/json"})
+				startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Content-Type", Value: "application/json"})
+				startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Authorization", Value: BA})
+
+				uuid, _ := uuidgen("APIGW-Ovirt-CloudInit")
+				__startVM, _ := json.MarshalIndent(startVM, "", "  ")
+				//fmt.Println("StartVMHeaders: ", string(__startVMHeaders))
+				addTask(uuid, string(__startVM), "", "APIGW", "VM Initialization", invoiceUUID, "1", "0")
+
+			}
+			//resp := _response{
+			//	Origin:  "ovirt-addvm",
+			//	Message: resposeInvoice
+			//	Code:    1000,
+			//}
+			return c.JSON(http.StatusOK, responseInvoiece)
+	*/
 }
+
+//func (o ovirt) EditVM(c echo.Context) error {
+//	resp := _response{
+//		Origin:  "ovirt-EditVM",
+//		Message: "Done",
+//		Code:    1000,
+//	}
+//	//b, _ := json.MarshalIndent(resp, "", "  ")
+//	//return c.String(http.StatusOK, string(b))
+//	return c.JSON(http.StatusOK, resp)
+//}
 func (o ovirt) ResetPassword(c echo.Context) error {
 	resp := _response{
 		Origin:  "ovirt-ResetPassword",
@@ -1580,10 +1963,32 @@ func vmStatistics(BA string, VMUUID string) (string, float64, float64, error) {
 		res, err := client.Do(req)
 		body, err := ioutil.ReadAll(res.Body)
 		defer res.Body.Close()
-		diskattachments := DiskAttachments{}
+		diskattachments := DiskAttachments{
+			DiskAttachment: []struct {
+				Active              string "json:\"active\""
+				Bootable            string "json:\"bootable\""
+				Interface           string "json:\"interface\""
+				LogicalName         string "json:\"logical_name\""
+				PassDiscard         string "json:\"pass_discard\""
+				ReadOnly            string "json:\"read_only\""
+				UsesScsiReservation string "json:\"uses_scsi_reservation\""
+				Disk                struct {
+					Href string "json:\"href\""
+					ID   string "json:\"id\""
+				} "json:\"disk\""
+				VM struct {
+					Href string "json:\"href\""
+					ID   string "json:\"id\""
+				} "json:\"vm\""
+				Href string "json:\"href\""
+				ID   string "json:\"id\""
+			}{},
+		}
 		_err := json.Unmarshal(body, &diskattachments)
 		if _err != nil {
 			fmt.Println("Error in vmStatistics 1: ", _err)
+			fmt.Println("Error: ", string(body))
+			return "", -1, -1, errors.New("unexpected Error")
 		}
 		for _, v := range diskattachments.DiskAttachment {
 			url := OvirtURL + "/ovirt-engine/api/disks/" + v.Disk.ID
@@ -1653,6 +2058,8 @@ func vmStatistics(BA string, VMUUID string) (string, float64, float64, error) {
 			_err := json.Unmarshal(body, &disk)
 			if _err != nil {
 				fmt.Println("Error in vmStatistics 2 : ", _err)
+				fmt.Println("Error: ", string(body))
+
 			}
 			defer res.Body.Close()
 			_disk = append(_disk, disk.ProvisionedSize)
@@ -1677,7 +2084,7 @@ func vmStatistics(BA string, VMUUID string) (string, float64, float64, error) {
 
 	res, err := client.Do(req)
 	body, err := ioutil.ReadAll(res.Body)
-	fmt.Println("Code: ", res.StatusCode)
+	// fmt.Println("Code: ", res.StatusCode, " VMUUID:", VMUUID)
 	if err != nil || res.StatusCode == 404 {
 		return "", -1, -1, errors.New("unexpected Error")
 	}
@@ -1687,6 +2094,9 @@ func vmStatistics(BA string, VMUUID string) (string, float64, float64, error) {
 	_err := json.Unmarshal(body, &_vmstatistics)
 	if _err != nil {
 		fmt.Println("Error in vmStatistics 3: ", _err)
+		fmt.Println("Error: ", string(body))
+
+		return "", -1, -1, errors.New("unexpected Error")
 	}
 	cpuUUID := _vmstatistics.Statistic[4].ID
 	memUsedUUID := _vmstatistics.Statistic[1].ID
@@ -1727,12 +2137,14 @@ func vmStatistics(BA string, VMUUID string) (string, float64, float64, error) {
 		req.Header.Add("Authorization", BA)
 
 		res, err := client.Do(req)
-		defer res.Body.Close()
 		body, err := ioutil.ReadAll(res.Body)
+		defer res.Body.Close()
 		cpuUsage := ItemUsage{}
 		_err := json.Unmarshal(body, &cpuUsage)
 		if _err != nil {
 			fmt.Println("Error in vmStatistics 4 ", _err)
+			fmt.Println("Error: ", string(body))
+
 		}
 		cpu = fmt.Sprintf("%f", cpuUsage.Values.Value[0].Datum)
 	}
@@ -1752,12 +2164,14 @@ func vmStatistics(BA string, VMUUID string) (string, float64, float64, error) {
 		req.Header.Add("Authorization", BA)
 
 		res, err := client.Do(req)
-		defer res.Body.Close()
 		body, err := ioutil.ReadAll(res.Body)
+		defer res.Body.Close()
 		memUsage := ItemUsage{}
 		_err := json.Unmarshal(body, &memUsage)
 		if _err != nil {
 			fmt.Println("Error in vmStatistics 5: ", _err)
+			fmt.Println("Error: ", string(body))
+
 		}
 		memUsed = fmt.Sprintf("%f", memUsage.Values.Value[0].Datum)
 	}
@@ -1777,12 +2191,16 @@ func vmStatistics(BA string, VMUUID string) (string, float64, float64, error) {
 		req.Header.Add("Authorization", BA)
 
 		res, err := client.Do(req)
-		defer res.Body.Close()
 		body, err := ioutil.ReadAll(res.Body)
+		defer res.Body.Close()
 		memUsage := ItemUsage{}
 		_err := json.Unmarshal(body, &memUsage)
 		if _err != nil {
 			fmt.Println("Error in vmStatistics 6: ", _err)
+			fmt.Println("Error: ", string(body))
+
+			return "", -1, -1, errors.New("unexpected Error")
+
 		}
 		memTotal = fmt.Sprintf("%f", memUsage.Values.Value[0].Datum)
 	}
@@ -2037,6 +2455,7 @@ func (o ovirt) vmDetails(c echo.Context) error {
 			NIC      string `json:"NIC"`
 			Traffic  string `json:"Traffic"`
 			Status   string `json:"Status"`
+			Period   string `json:"Period"`
 			Name     string `json:"Name"`
 			Template string `json:"Template"`
 		} `json:"message"`
@@ -2051,6 +2470,7 @@ func (o ovirt) vmDetails(c echo.Context) error {
 			NIC      string `json:"NIC"`
 			Traffic  string `json:"Traffic"`
 			Status   string `json:"Status"`
+			Period   string `json:"Period"`
 			Name     string `json:"Name"`
 			Template string `json:"Template"`
 		}{
@@ -2060,6 +2480,7 @@ func (o ovirt) vmDetails(c echo.Context) error {
 			NIC:     fmt.Sprintf("%d", nic),
 			Traffic: vmJsonDetails[5].Value,
 			Status:  _vmstatus.Status,
+			Period:  "3",
 			// v.Name[len(login(BA).AuthenticatedUser.ID)+3:]
 			Name:     _vmstatus.Name[len(login(BA).AuthenticatedUser.ID)+3:],
 			Template: vmJsonDetails[7].Value,
@@ -2454,7 +2875,23 @@ func (o ovirt) VNC(c echo.Context) error {
 	res, err := client.Do(req)
 	body, err := ioutil.ReadAll(res.Body)
 	defer res.Body.Close()
-	_graphicConsoleList := graphicConsoleList{}
+	_graphicConsoleList := graphicConsoleList{
+		GraphicsConsole: []struct {
+			Protocol string "json:\"protocol\""
+			VM       struct {
+				Href string "json:\"href\""
+				ID   string "json:\"id\""
+			} "json:\"vm\""
+			Actions struct {
+				Link []struct {
+					Href string "json:\"href\""
+					Rel  string "json:\"rel\""
+				} "json:\"link\""
+			} "json:\"actions\""
+			Href string "json:\"href\""
+			ID   string "json:\"id\""
+		}{},
+	}
 	err = json.Unmarshal(body, &_graphicConsoleList)
 	urlvncfile := OvirtURL + "/ovirt-engine/api/vms/" + vmuuid + "/graphicsconsoles/" + _graphicConsoleList.GraphicsConsole[0].ID + "/remoteviewerconnectionfile"
 	client2 := &http.Client{}
@@ -2493,7 +2930,7 @@ func (o ovirt) VNC(c echo.Context) error {
 
 	resp := _response{
 		Origin:  "ovirt-VNC",
-		Message: "http://zi-cloud.ir:" + fmt.Sprintf("%d", lport) + "/vnc.html?autoconnect=true&password=" + strings.Split(password, "=")[1],
+		Message: "https://vnc.zi-cloud.ir:" + fmt.Sprintf("%d", lport) + "/vnc.html?autoconnect=true&show_dot=true&password=" + strings.Split(password, "=")[1],
 		Code:    1000,
 	}
 	return c.JSON(http.StatusOK, resp)
@@ -2742,8 +3179,8 @@ func (o ovirt) vmHistory(c echo.Context) error {
 	req.Header.Add("Authorization", BA)
 
 	res, err := client.Do(req)
-	defer res.Body.Close()
 	body, err := ioutil.ReadAll(res.Body)
+	defer res.Body.Close()
 	_VMStatistics := VMStatistics{}
 	err = json.Unmarshal(body, &_VMStatistics)
 	_VMStatisticsResponse := VMStatisticsResponse{

+ 1 - 1
token.go

@@ -45,7 +45,7 @@ func generateTokenPair(user userInfo, cockieStr string) (map[string]string, erro
 	rtClaims["sub"] = 1
 	rtClaims["IPAToken"] = claims["IPAToken"]
 	rtClaims["name"] = claims["name"]
-	rtClaims["exp"] = time.Now().Add(time.Hour * 24).Unix()
+	rtClaims["exp"] = time.Now().Add(time.Hour * 1).Unix()
 
 	rt, err := refreshToken.SignedString([]byte("secret"))
 	if err != nil {