Browse Source

1: Change AddVM/EditVM procedure to include Payment Procedure
2: add ovirtPayment method to confirm specific payment was successful (to start create/edit procedure)
3: Other bug Fixes

torabkheslat 4 years ago
parent
commit
842f679b27
4 changed files with 528 additions and 324 deletions
  1. 17 15
      handler.go
  2. 22 38
      main.go
  3. 487 268
      ovirt.go
  4. 2 3
      token.go

+ 17 - 15
handler.go

@@ -192,10 +192,10 @@ func getUserInfo(token string, username string) userInfo {
 	res, err := client.Do(req)
 	defer res.Body.Close()
 	body, err := ioutil.ReadAll(res.Body)
-	//fmt.Println("Getting Data for Response: ", res.Status)
+	//fmt.Println("Getting Data for Response: ", body)
 	user := userInfo{}
 	json.Unmarshal(body, &user)
-	fmt.Println("Getting Data for User: ", user.Result.Result.Uidnumber)
+	//fmt.Println("Getting Data for User: ", user.Result.Result.Uidnumber)
 	return user
 }
 func (h *handler) uuidgen(c echo.Context) error {
@@ -377,7 +377,7 @@ func (h *handler) addUser(c echo.Context) error {
 		//return c.JSON(http.StatusBadRequest, _apiErr)
 	}
 	shortLink := setResetKey(ciphertext, username)
-	go sendMail("Welcome to ZiCloud\r\n Your temporary link is :\r\n https://zicloud.com/reset/"+url.QueryEscape(shortLink), "Welcome to ZiCloud", mail)
+	go sendMail("Welcome to ZiCloud\r\n Your temporary link is :\r\n http://zi-cloud.ir/reset/"+url.QueryEscape(shortLink), "Welcome to ZiCloud", mail)
 	//go sendMail("Welcome to ZiCloud\r\n Your temporary link is :\r\n https://zicloud.com/reset/"+url.QueryEscape(ciphertext), "Welcome to ZiCloud", mail)
 	resp := _response{
 		Origin:  "addUser",
@@ -458,7 +458,7 @@ func (h *handler) resetUser(c echo.Context) error {
 	if len(key) < 5 {
 		resp := _response{
 			Origin:  "resetUser",
-			Message: "Object Not found",
+			Message: "Link has been expired",
 			Code:    1001,
 		}
 		//b, _ := json.MarshalIndent(resp, "", "  ")
@@ -628,8 +628,10 @@ func (h *handler) token(c echo.Context) error {
 	hashChannel_ <- _sha256[:]
 	token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
 	username := claims["name"].(string)
+	//fmt.Println("User: ",username)
+	//fmt.Println("Token : ",token)
 	_user := getUserInfo(token, username)
-	//fmt.Println(user.Result)
+	//fmt.Println(_user.Result)
 	newtokens, err := generateTokenPair(_user, token)
 	if err != nil {
 		return err
@@ -884,7 +886,7 @@ func (h *handler) ListServices(c echo.Context) error {
 	totalCount := 0
 	activeVMCount := 0
 	totalVMCount := 0
-	var cpu , mem float64
+	var cpu, mem float64
 	var _type, service_uuid, active, objectName string
 	for results.Next() {
 		err := results.Scan(&_type, &service_uuid, &active, &objectName)
@@ -902,9 +904,9 @@ func (h *handler) ListServices(c echo.Context) error {
 				activeCount++
 				activeVMCount++
 				//fmt.Println(vmStatistics(BA,service_uuid))
-				_,_cpu,_mem:=vmStatistics(BA,service_uuid)
-				cpu+=_cpu
-				mem+=_mem
+				_, _cpu, _mem := vmStatistics(BA, service_uuid)
+				cpu += _cpu
+				mem += _mem
 			}
 			totalCount++
 			totalVMCount++
@@ -926,8 +928,8 @@ func (h *handler) ListServices(c echo.Context) error {
 			ActiveCount   string `json:"ActiveCount"`
 			ActiveVMCount string `json:"ActiveVMCount"`
 			TotalVMCount  string `json:"TotalVMCount"`
-			TotalCPUUsage  string `json:"TotalCPUUsage"`
-			TotalMemUsage  string `json:"TotalMemUsage"`
+			TotalCPUUsage string `json:"TotalCPUUsage"`
+			TotalMemUsage string `json:"TotalMemUsage"`
 		} `json:"message"`
 		Origin string `json:"origin"`
 		Code   int    `json:"code"`
@@ -938,15 +940,15 @@ func (h *handler) ListServices(c echo.Context) error {
 			ActiveCount   string `json:"ActiveCount"`
 			ActiveVMCount string `json:"ActiveVMCount"`
 			TotalVMCount  string `json:"TotalVMCount"`
-			TotalCPUUsage  string `json:"TotalCPUUsage"`
-			TotalMemUsage  string `json:"TotalMemUsage"`
+			TotalCPUUsage string `json:"TotalCPUUsage"`
+			TotalMemUsage string `json:"TotalMemUsage"`
 		}{
 			TotalCount:    strconv.Itoa(totalCount),
 			ActiveCount:   strconv.Itoa(activeCount),
 			ActiveVMCount: strconv.Itoa(activeVMCount),
 			TotalVMCount:  strconv.Itoa(totalVMCount),
-			TotalCPUUsage:  fmt.Sprintf("%f", 100*cpu/float64(activeVMCount)),
-			TotalMemUsage:  fmt.Sprintf("%f", 100*mem/float64(activeVMCount)),
+			TotalCPUUsage: fmt.Sprintf("%f", 100*cpu/float64(activeVMCount)),
+			TotalMemUsage: fmt.Sprintf("%f", 100*mem/float64(activeVMCount)),
 		},
 		Origin: "ListServices",
 		Code:   1000,

+ 22 - 38
main.go

@@ -14,6 +14,7 @@ import (
 	"github.com/labstack/echo"
 	"github.com/labstack/echo/middleware"
 	"io"
+	"io/ioutil"
 	"log"
 	"log/syslog"
 	"net/http"
@@ -42,6 +43,7 @@ func uuidgen(resource string) (string, int) {
 		return "resource name should be at least 3 characters!", 1001
 	}
 
+	//fmt.Println("uuidGen for ", id, " at ", resource)
 	{
 		db, err := sql.Open("mysql", MySQLUSER+":"+MySQLPASS+"@tcp(127.0.0.1:3306)/zicloud")
 		if err != nil {
@@ -104,7 +106,7 @@ func main() {
 		os.Exit(1)
 	}
 	s := gocron.NewScheduler()
-	s.Every(1).Seconds().Do(task)
+	s.Every(5).Seconds().Do(task)
 
 	go s.Start()
 	echoHandler := echo.New()
@@ -145,11 +147,13 @@ func main() {
 	echoHandler.POST("/ovirtEditVM", iaas.EditVM, isLoggedIn)
 	echoHandler.POST("/ovirtResetPassword", iaas.ResetPassword, isLoggedIn)
 	echoHandler.POST("/vmDetails", iaas.vmDetails, isLoggedIn)
+	echoHandler.POST("/ovirtPayment", iaas.ovirtPayment, isLoggedIn, isAdmin)
 
 	echoHandler.Logger.Fatal(echoHandler.Start(os.Args[1] + ":" + os.Args[2]))
 }
 func encrypt(key []byte, text string) string {
 	// key := []byte(keyText)
+	//fmt.Println("Encrypt by: ", key)
 	plaintext := []byte(text)
 	block, err := aes.NewCipher(key)
 	if err != nil {
@@ -174,7 +178,7 @@ func encrypt(key []byte, text string) string {
 }
 func decrypt(key []byte, cryptoText string) string {
 	ciphertext, _ := base64.URLEncoding.DecodeString(cryptoText)
-
+	//fmt.Println("Decrypt by: ", key)
 	block, err := aes.NewCipher(key)
 	if err != nil {
 		fmt.Sprintf("decrypt got error")
@@ -196,7 +200,6 @@ func decrypt(key []byte, cryptoText string) string {
 
 	// XORKeyStream can work in-place if the two arguments are the same.
 	stream.XORKeyStream(ciphertext, ciphertext)
-
 	return fmt.Sprintf("%s", ciphertext)
 }
 func task() {
@@ -205,7 +208,7 @@ func task() {
 		TaskAPICall    string `json:"taskapicall"`
 		Ruuid          string `json:"ruuid"`
 		CronExpression string `json:"cronexpression"`
-		Type           string `json:"type"`
+		Type           string `json:"type"` //0: createVM , 1: VMInitialization
 	}
 	//fmt.Println("Task is being performed.")
 	db, err := sql.Open("mysql", MySQLUSER+":"+MySQLPASS+"@tcp(127.0.0.1:3306)/zicloud")
@@ -216,14 +219,15 @@ func task() {
 		if err != nil {
 			panic(err.Error()) // proper error handling instead of panic in your app
 		}
-		i := 0
-		i, _ = strconv.Atoi(res.Type)
-		if i == 1 {
+		taskType := 0
+		taskType, _ = strconv.Atoi(res.Type)
+		if taskType == 0 {
+			createVM(res.Ruuid, res.TaskAPICall, res.UUID)
+		} else if taskType == 1 {
 			VMInitialization(res.Ruuid, res.TaskAPICall, res.UUID)
-		} else if i == 2 {
+		} else if taskType == 2 {
 
-		} else
-		{
+		} else {
 
 		}
 		//fmt.Println("query ruuid: ", res.Ruuid)
@@ -239,38 +243,16 @@ func task() {
 	//fmt.Println("down",iaas.vmStatus("4f0e58ff-fb75-4a3d-9262-bd3714db52a6"))
 	//fmt.Println("up",iaas.vmStatus("6b84a5dc-1c83-43e0-9ea6-dd86413bccc0"))
 }
-func VMInitialization(relatedUuid string, apiCall string, uuid string) {
-	iaas := &ovirt{}
-	status := iaas.vmStatus(relatedUuid)
-	//fmt.Println("VM :", relatedUuid, " is now: ", status)
-	if status == "down" {
-		//fmt.Println("APICall: ", apiCall)
-		startVM := addVMTask{}
-		//b, _ := json.Marshal(apiCall)
-		_err := json.Unmarshal([]byte(apiCall), &startVM)
-		if _err != nil {
-			fmt.Println("Error in VMInitialization: ", _err.Error())
-		}
-		//fmt.Println("calling initialization for VM :", relatedUuid)
-		_sha256 := sha256.Sum256([]byte(relatedUuid))
-		var hashChannel_ = make(chan []byte, 1)
-		hashChannel_ <- _sha256[:]
-		//fmt.Println(" startVM.JSON: ", startVM.JSON)
-		startVM.JSON = decrypt(<-hashChannel_, startVM.JSON)
-		//fmt.Println("decrypted json: ",startVM.JSON)
-		runAPICall(startVM)
-		toggleTask(uuid, 0)
-	}
-}
 func addTask(uuid string, taskAPICall string, cronExpression string, origin string, description string, related_uuid string, _type string, active string) string {
 	{
 		/*
 			types:
-				1: VM Inisialize
+				0: VM Create
+				1: VM Initialize
 				2: VM Start
 				3: VM Stop
 		*/
-		//fmt.Println("Add Task:", taskAPICall)
+		//fmt.Println("Add Task:", uuid)
 		db, err := sql.Open("mysql", MySQLUSER+":"+MySQLPASS+"@tcp(127.0.0.1:3306)/zicloud")
 		if err != nil {
 		}
@@ -305,12 +287,12 @@ func toggleTask(uuid string, active int) {
 	defer update.Close()
 
 }
-func runAPICall(apiCall addVMTask) {
+func runAPICall(apiCall addVMTask) []byte {
 	url := apiCall.URL
 	method := apiCall.Method
 	__json := apiCall.JSON
-	client := &http.Client{
-	}
+	//fmt.Println("runAPICALL: ", __json)
+	client := &http.Client{}
 	payload := strings.NewReader(__json)
 	req, err := http.NewRequest(method, url, payload)
 	_headers := apiCall.Headers
@@ -322,6 +304,8 @@ func runAPICall(apiCall addVMTask) {
 	}
 	res, err := client.Do(req)
 	defer res.Body.Close()
+	body, _ := ioutil.ReadAll(res.Body)
+	return body
 }
 func VMPowerMng(relatedUuid string, apiCall string, uuid string) {
 	startVM := addVMTask{}

+ 487 - 268
ovirt.go

@@ -24,8 +24,7 @@ func login(BA string) OvirtObject {
 	url := OvirtURL + "/ovirt-engine/api"
 	method := "GET"
 
-	client := &http.Client{
-	}
+	client := &http.Client{}
 	req, err := http.NewRequest(method, url, nil)
 
 	if err != nil {
@@ -84,13 +83,47 @@ type TaskHeader struct {
 }
 type addVMTask struct {
 	URL     string `json:"url"`
-	JSON    string `json:"__json"`
+	JSON    string `json:__json`
 	Method  string `json:"method"`
 	Headers []struct {
 		Name  string `json:"Name,omitempty"`
 		Value string `json:"Value,omitempty"`
 	} `json:"headers"`
 }
+type AddVMRequest struct {
+	URL  string `json:"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"`
+	} `json:"JSON"`
+	Method  string `json:"method"`
+	Headers []struct {
+		Name  string `json:"Name"`
+		Value string `json:"Value"`
+	} `json:"headers"`
+}
 type VMStatistics struct {
 	Statistic []struct {
 		Kind   string `json:"kind"`
@@ -255,11 +288,10 @@ func (o ovirt) vmStatus(uuid string) string {
 	}
 	//url := "https://ovirt-cl.zi-tel.com/ovirt-engine/api/vms/c1a44128-6c6c-406b-99d8-4a68a99380c9"
 	url := OvirtURL + "/ovirt-engine/api/vms/" + uuid
-	//fmt.Println("Url:" ,url)
+	//fmt.Println("VMSTATUS UUID:" ,uuid)
 	method := "GET"
 
-	client := &http.Client{
-	}
+	client := &http.Client{}
 	req, err := http.NewRequest(method, url, nil)
 
 	if err != nil {
@@ -267,6 +299,7 @@ func (o ovirt) vmStatus(uuid string) string {
 	}
 	req.Header.Add("Version", "4")
 	req.Header.Add("Accept", "application/json")
+	//TODO: replace BA
 	req.Header.Add("Authorization", "Basic YWRtaW5AaW50ZXJuYWw6a2VsYW5zaCBqMw==")
 
 	res, err := client.Do(req)
@@ -277,153 +310,11 @@ func (o ovirt) vmStatus(uuid string) string {
 	_vmstatus := vmStatus{}
 	_err := json.Unmarshal(body, &_vmstatus)
 	if _err != nil {
-		fmt.Println("Error: ", _err)
+		fmt.Println("Error in vmStatus ", _err)
 	}
 	return _vmstatus.Status
 }
 func (o ovirt) addvm(c echo.Context) error {
-	type AddVMResponse struct {
-		NextRunConfigurationExists string `json:"next_run_configuration_exists"`
-		NumaTuneMode               string `json:"numa_tune_mode"`
-		Status                     string `json:"status"`
-		StopTime                   int64  `json:"stop_time"`
-		OriginalTemplate           struct {
-			Href string `json:"href"`
-			ID   string `json:"id"`
-		} `json:"original_template"`
-		Template struct {
-			Href string `json:"href"`
-			ID   string `json:"id"`
-		} `json:"template"`
-		Actions struct {
-			Link []struct {
-				Href string `json:"href"`
-				Rel  string `json:"rel"`
-			} `json:"link"`
-		} `json:"actions"`
-		Name        string `json:"name"`
-		Description string `json:"description"`
-		Comment     string `json:"comment"`
-		Href        string `json:"href"`
-		ID          string `json:"id"`
-		Bios        struct {
-			BootMenu struct {
-				Enabled string `json:"enabled"`
-			} `json:"boot_menu"`
-			Type string `json:"type"`
-		} `json:"bios"`
-		Console struct {
-			Enabled string `json:"enabled"`
-		} `json:"console"`
-		CPU struct {
-			Architecture string `json:"architecture"`
-			Topology     struct {
-				Cores   string `json:"cores"`
-				Sockets string `json:"sockets"`
-				Threads string `json:"threads"`
-			} `json:"topology"`
-		} `json:"cpu"`
-		Display struct {
-			AllowOverride       string `json:"allow_override"`
-			CopyPasteEnabled    string `json:"copy_paste_enabled"`
-			DisconnectAction    string `json:"disconnect_action"`
-			FileTransferEnabled string `json:"file_transfer_enabled"`
-			Monitors            string `json:"monitors"`
-			SingleQxlPci        string `json:"single_qxl_pci"`
-			SmartcardEnabled    string `json:"smartcard_enabled"`
-			Type                string `json:"type"`
-		} `json:"display"`
-		Initialization struct {
-			AuthorizedSSHKeys        string `json:"authorized_ssh_keys"`
-			CloudInitNetworkProtocol string `json:"cloud_init_network_protocol"`
-			CustomScript             string `json:"custom_script"`
-			HostName                 string `json:"host_name"`
-			NicConfigurations        struct {
-			} `json:"nic_configurations"`
-			RegenerateSSHKeys string `json:"regenerate_ssh_keys"`
-			UserName          string `json:"user_name"`
-		} `json:"initialization"`
-		Io struct {
-			Threads string `json:"threads"`
-		} `json:"io"`
-		Memory    string `json:"memory"`
-		Migration struct {
-			AutoConverge string `json:"auto_converge"`
-			Compressed   string `json:"compressed"`
-			Encrypted    string `json:"encrypted"`
-		} `json:"migration"`
-		Origin string `json:"origin"`
-		Os     struct {
-			Boot struct {
-				Devices struct {
-					Device []string `json:"device"`
-				} `json:"devices"`
-			} `json:"boot"`
-			Type string `json:"type"`
-		} `json:"os"`
-		Sso struct {
-			Methods struct {
-				Method []struct {
-					ID string `json:"id"`
-				} `json:"method"`
-			} `json:"methods"`
-		} `json:"sso"`
-		Stateless string `json:"stateless"`
-		Type      string `json:"type"`
-		Usb       struct {
-			Enabled string `json:"enabled"`
-		} `json:"usb"`
-		Cluster struct {
-			Href string `json:"href"`
-			ID   string `json:"id"`
-		} `json:"cluster"`
-		Quota struct {
-			ID string `json:"id"`
-		} `json:"quota"`
-		CreationStatus string `json:"creation_status"`
-		Link           []struct {
-			Href string `json:"href"`
-			Rel  string `json:"rel"`
-		} `json:"link"`
-		CPUShares        string `json:"cpu_shares"`
-		CreationTime     int64  `json:"creation_time"`
-		DeleteProtected  string `json:"delete_protected"`
-		HighAvailability struct {
-			Enabled  string `json:"enabled"`
-			Priority string `json:"priority"`
-		} `json:"high_availability"`
-		LargeIcon struct {
-			Href string `json:"href"`
-			ID   string `json:"id"`
-		} `json:"large_icon"`
-		MemoryPolicy struct {
-			Ballooning string `json:"ballooning"`
-			Guaranteed string `json:"guaranteed"`
-			Max        string `json:"max"`
-		} `json:"memory_policy"`
-		MigrationDowntime  string `json:"migration_downtime"`
-		MultiQueuesEnabled string `json:"multi_queues_enabled"`
-		RngDevice          struct {
-			Source string `json:"source"`
-		} `json:"rng_device"`
-		SmallIcon struct {
-			Href string `json:"href"`
-			ID   string `json:"id"`
-		} `json:"small_icon"`
-		SoundcardEnabled            string `json:"soundcard_enabled"`
-		StartPaused                 string `json:"start_paused"`
-		StorageErrorResumeBehaviour string `json:"storage_error_resume_behaviour"`
-		TimeZone                    struct {
-			Name string `json:"name"`
-		} `json:"time_zone"`
-		VirtioScsi struct {
-			Enabled string `json:"enabled"`
-		} `json:"virtio_scsi"`
-		CPUProfile struct {
-			Href string `json:"href"`
-			ID   string `json:"id"`
-		} `json:"cpu_profile"`
-	}
 	user := c.Get("user").(*jwt.Token)
 	claims := user.Claims.(jwt.MapClaims)
 	_sha256 := sha256.Sum256([]byte(string(claims["name"].(string))))
@@ -432,8 +323,6 @@ func (o ovirt) addvm(c echo.Context) error {
 	token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
 	_BA := strings.Split(token, ";")
 	BA := _BA[len(_BA)-2]
-	//fmt.Println("Token: ", token)
-	//fmt.Println("BA: ", BA)
 	var vmname, vmdescr, vmcomment, templatename, cpuSock, cpuCore, cpuThread, mem string
 	vmname = c.FormValue("VmName")
 	vmdescr = c.FormValue("VmDescr")
@@ -447,64 +336,163 @@ func (o ovirt) addvm(c echo.Context) error {
 	mem = c.FormValue("VmMem")
 	url := OvirtURL + "/ovirt-engine/api/vms"
 	method := "POST"
-	_json := fmt.Sprintf(`
-{
-    "name": "%s",
-    "description": "%s",
-    "comment": "%s",
-    "cluster": {
-        "name": "Default"
-    },
-    "template": {
-        "name": "%s"
-    },
-    "cpu": {
-        "topology": {
-            "sockets": "%s",
-            "cores": "%s",
-            "threads": "%s"
-        }
-    },
-    "memory": "%s",
-    "memory_policy": {
-        "ballooning": "true",
-        "guaranteed": "%s",
-        "over_commit": {
-            "percent": "10"
-        }
-    }
-}
-`, vmname, vmdescr, vmcomment, templatename, cpuSock, cpuCore, cpuThread, mem, mem)
-	payload := strings.NewReader(_json)
-	//tr := &http.Transport{
-	//	TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
+	//TODO: Encrypt this Json
+	//	_json := fmt.Sprintf(`
+	//{
+	//    "name": "%s",
+	//    "description": "%s",
+	//    "comment": "%s",
+	//    "cluster": {
+	//        "name": "Default"
+	//    },
+	//    "template": {
+	//        "name": "%s"
+	//    },
+	//    "cpu": {
+	//        "topology": {
+	//            "sockets": "%s",
+	//            "cores": "%s",
+	//            "threads": "%s"
+	//        }
+	//    },
+	//    "memory": "%s",
+	//    "memory_policy": {
+	//        "ballooning": "true",
+	//        "guaranteed": "%s",
+	//        "over_commit": {
+	//            "percent": "10"
+	//        }
+	//    }
 	//}
-	client := &http.Client{}
-	req, err := http.NewRequest(method, url, payload)
-	if err != nil {
-		fmt.Println(err)
-	}
-	req.Header.Add("Version", "4")
-	req.Header.Add("Accept", "application/json")
-	req.Header.Add("Authorization", BA)
-	req.Header.Add("Content-Type", "application/json")
-	res, err := client.Do(req)
-	body, err := ioutil.ReadAll(res.Body)
-	//fmt.Println("len: ", len(_json))
-	//fmt.Println("res:", res)
-	if err != nil || res.StatusCode != 202 {
-		resp := _response{
-			Origin:  "ovirt-addvm",
-			Message: res.Status,
-			Code:    1001,
-		}
-		b, _ := json.MarshalIndent(resp, "", "  ")
-		return c.String(http.StatusBadRequest, string(b))
+	//`, vmname, vmdescr, vmcomment, templatename, cpuSock, cpuCore, cpuThread, mem, mem)
+	// Change as task
+	//change to task//	payload := strings.NewReader(_json)
+	//change to task//	//tr := &http.Transport{
+	//change to task//	//	TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
+	//change to task//	//}
+	//change to task//	client := &http.Client{}
+	//change to task//	req, err := http.NewRequest(method, url, payload)
+	//change to task//	if err != nil {
+	//change to task//		fmt.Println(err)
+	//change to task//	}
+	//change to task//	req.Header.Add("Version", "4")
+	//change to task//	req.Header.Add("Accept", "application/json")
+	//change to task//	req.Header.Add("Authorization", BA)
+	//change to task//	req.Header.Add("Content-Type", "application/json")
+	//change to task//	res, err := client.Do(req)
+	//change to task//	body, err := ioutil.ReadAll(res.Body)
+	//change to task//	//fmt.Println("len: ", len(_json))
+	//change to task//	//fmt.Println("res:", res)
+	//change to task//	if err != nil || res.StatusCode != 202 {
+	//change to task//		resp := _response{
+	//change to task//			Origin:  "ovirt-addvm",
+	//change to task//			Message: res.Status,
+	//change to task//			Code:    1001,
+	//change to task//		}
+	//change to task//		b, _ := json.MarshalIndent(resp, "", "  ")
+	//change to task//		return c.String(http.StatusBadRequest, string(b))
+	//change to task//	}
+	//change to task//	defer res.Body.Close()
+	//addvmresponse := AddVMResponse{}O
+	newvm := 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,
 	}
-	defer res.Body.Close()
-	addvmresponse := AddVMResponse{}
-	err = json.Unmarshal(body, &addvmresponse)
-	//fmt.Println("User UID:", claims["IPAUid"].(string))
+	newvm.Headers = append(newvm.Headers, struct {
+		Name  string `json:"Name"`
+		Value string `json:"Value"`
+	}{
+		Name:  "Accept",
+		Value: "application/json",
+	})
+	newvm.Headers = append(newvm.Headers, struct {
+		Name  string `json:"Name"`
+		Value string `json:"Value"`
+	}{
+		Name:  "Authorization",
+		Value: BA,
+	})
+	newvm.Headers = append(newvm.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")
+	__createVM, _ := json.MarshalIndent(newvm, "", "  ")
+	// 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 {
@@ -517,31 +505,27 @@ func (o ovirt) addvm(c echo.Context) error {
 			return c.String(http.StatusBadRequest, string(b))
 		}
 		defer db.Close()
-		insert, err := db.Query("INSERT INTO service_profile VALUES ( '" + addvmresponse.ID + "'," +
+		insert, err := db.Query("INSERT INTO service_profile VALUES ( '" + invoiceUUID + "'," +
 			"'" + claims["IPAUid"].(string) + "'," +
 			"'" + "VM" + "'," +
-			"'" + addvmresponse.ID + "'," +
+			"'" + "" + "'," +
 			"'" + login(BA).AuthenticatedUser.ID + "'," +
 			"NOW()" + "," +
 			"NOW() ," +
-			"true" + "," +
-			"'" + addvmresponse.Name + "' )")
+			"false" + "," +
+			"'" + vmname + "'," +
+			"'" + invoiceUUID + "' )")
 		defer insert.Close()
-
-	}
-	if err != nil {
-		resp := _response{
-			Origin:  "ovirt-addvm",
-			Message: "Error on pars AddVMResponse: " + err.Error(),
-			Code:    1001,
+		if err != nil {
+			fmt.Println("Error in addVM: ", err.Error())
 		}
-		//b, _ := json.MarshalIndent(resp, "", "  ")
-		return c.JSON(http.StatusBadRequest, resp)
-		//return c.String(http.StatusBadRequest, string(b))
+
 	}
+
+	// Start Task
 	{
 
-		url := OvirtURL + "/ovirt-engine/api/vms/" + addvmresponse.ID + "/start"
+		url := OvirtURL + "/ovirt-engine/api/vms/" + invoiceUUID + "/start"
 		method := "POST"
 		nicAddress := "172.20.15.251"
 		nicMask := "255.255.255.0"
@@ -575,16 +559,7 @@ func (o ovirt) addvm(c echo.Context) error {
     }
 }
 `, sshKey, rootpass, nicAddress, nicMask, nicGW)
-		//client := &http.Client{
-		//}
-		//payload := strings.NewReader(__json)
-		//req, err := http.NewRequest(method, url, payload)
-		//
-		//if err != nil {
-		//	fmt.Println(err)
-		//}
-		//var startVMHeaders []TaskHeader
-		sha256 := sha256.Sum256([]byte(addvmresponse.ID))
+		sha256 := sha256.Sum256([]byte(invoiceUUID))
 		var hashChannel = make(chan []byte, 1)
 		hashChannel <- sha256[:]
 		___json := encrypt(<-hashChannel, __json)
@@ -599,26 +574,17 @@ func (o ovirt) addvm(c echo.Context) error {
 		startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Content-Type", Value: "application/json"})
 		startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Authorization", Value: BA})
 
-		//req.Header.Add("Version", "4")
-		//req.Header.Add("Accept", "application/json")
-		//req.Header.Add("Authorization", BA)
-		//req.Header.Add("Content-Type", "application/json")
-		//
-		//res, err := client.Do(req)
-		//defer res.Body.Close()
-		uuid, _ := uuidgen("APIGW-Ovirt")
+		uuid, _ := uuidgen("APIGW-Ovirt-CloudInit")
 		__startVM, _ := json.MarshalIndent(startVM, "", "  ")
 		//fmt.Println("StartVMHeaders: ", string(__startVMHeaders))
-		addTask(uuid, string(__startVM), "", "APIGW", "VM Initialization", addvmresponse.ID, "1", "1")
+		addTask(uuid, string(__startVM), "", "APIGW", "VM Initialization", invoiceUUID, "1", "0")
 	}
 	resp := _response{
 		Origin:  "ovirt-addvm",
-		Message: "Done",
+		Message: invoiceUUID,
 		Code:    1000,
 	}
-	//b, _ := json.MarshalIndent(resp, "", "  ")
 	return c.JSON(http.StatusOK, resp)
-	//return c.String(http.StatusOK, string(b))
 }
 func (o ovirt) listVM(c echo.Context) error {
 	user := c.Get("user").(*jwt.Token)
@@ -630,8 +596,7 @@ func (o ovirt) listVM(c echo.Context) error {
 	_BA := strings.Split(token, ";")
 	BA := _BA[len(_BA)-2]
 	url := OvirtURL + "/ovirt-engine/api/vms"
-	client := &http.Client{
-	}
+	client := &http.Client{}
 	req, err := http.NewRequest("GET", url, nil)
 
 	if err != nil {
@@ -911,6 +876,248 @@ func (o ovirt) ResetPassword(c echo.Context) error {
 	return c.JSON(http.StatusOK, resp)
 }
 
+func createVM(invoice_uuid string, apiJson string, uuid string) {
+	type AddVMResponse struct {
+		NextRunConfigurationExists string `json:"next_run_configuration_exists"`
+		NumaTuneMode               string `json:"numa_tune_mode"`
+		Status                     string `json:"status"`
+		StopTime                   int64  `json:"stop_time"`
+		OriginalTemplate           struct {
+			Href string `json:"href"`
+			ID   string `json:"id"`
+		} `json:"original_template"`
+		Template struct {
+			Href string `json:"href"`
+			ID   string `json:"id"`
+		} `json:"template"`
+		Actions struct {
+			Link []struct {
+				Href string `json:"href"`
+				Rel  string `json:"rel"`
+			} `json:"link"`
+		} `json:"actions"`
+		Name        string `json:"name"`
+		Description string `json:"description"`
+		Comment     string `json:"comment"`
+		Href        string `json:"href"`
+		ID          string `json:"id"`
+		Bios        struct {
+			BootMenu struct {
+				Enabled string `json:"enabled"`
+			} `json:"boot_menu"`
+			Type string `json:"type"`
+		} `json:"bios"`
+		Console struct {
+			Enabled string `json:"enabled"`
+		} `json:"console"`
+		CPU struct {
+			Architecture string `json:"architecture"`
+			Topology     struct {
+				Cores   string `json:"cores"`
+				Sockets string `json:"sockets"`
+				Threads string `json:"threads"`
+			} `json:"topology"`
+		} `json:"cpu"`
+		Display struct {
+			AllowOverride       string `json:"allow_override"`
+			CopyPasteEnabled    string `json:"copy_paste_enabled"`
+			DisconnectAction    string `json:"disconnect_action"`
+			FileTransferEnabled string `json:"file_transfer_enabled"`
+			Monitors            string `json:"monitors"`
+			SingleQxlPci        string `json:"single_qxl_pci"`
+			SmartcardEnabled    string `json:"smartcard_enabled"`
+			Type                string `json:"type"`
+		} `json:"display"`
+		Initialization struct {
+			AuthorizedSSHKeys        string `json:"authorized_ssh_keys"`
+			CloudInitNetworkProtocol string `json:"cloud_init_network_protocol"`
+			CustomScript             string `json:"custom_script"`
+			HostName                 string `json:"host_name"`
+			NicConfigurations        struct {
+			} `json:"nic_configurations"`
+			RegenerateSSHKeys string `json:"regenerate_ssh_keys"`
+			UserName          string `json:"user_name"`
+		} `json:"initialization"`
+		Io struct {
+			Threads string `json:"threads"`
+		} `json:"io"`
+		Memory    string `json:"memory"`
+		Migration struct {
+			AutoConverge string `json:"auto_converge"`
+			Compressed   string `json:"compressed"`
+			Encrypted    string `json:"encrypted"`
+		} `json:"migration"`
+		Origin string `json:"origin"`
+		Os     struct {
+			Boot struct {
+				Devices struct {
+					Device []string `json:"device"`
+				} `json:"devices"`
+			} `json:"boot"`
+			Type string `json:"type"`
+		} `json:"os"`
+		Sso struct {
+			Methods struct {
+				Method []struct {
+					ID string `json:"id"`
+				} `json:"method"`
+			} `json:"methods"`
+		} `json:"sso"`
+		Stateless string `json:"stateless"`
+		Type      string `json:"type"`
+		Usb       struct {
+			Enabled string `json:"enabled"`
+		} `json:"usb"`
+		Cluster struct {
+			Href string `json:"href"`
+			ID   string `json:"id"`
+		} `json:"cluster"`
+		Quota struct {
+			ID string `json:"id"`
+		} `json:"quota"`
+		CreationStatus string `json:"creation_status"`
+		Link           []struct {
+			Href string `json:"href"`
+			Rel  string `json:"rel"`
+		} `json:"link"`
+		CPUShares        string `json:"cpu_shares"`
+		CreationTime     int64  `json:"creation_time"`
+		DeleteProtected  string `json:"delete_protected"`
+		HighAvailability struct {
+			Enabled  string `json:"enabled"`
+			Priority string `json:"priority"`
+		} `json:"high_availability"`
+		LargeIcon struct {
+			Href string `json:"href"`
+			ID   string `json:"id"`
+		} `json:"large_icon"`
+		MemoryPolicy struct {
+			Ballooning string `json:"ballooning"`
+			Guaranteed string `json:"guaranteed"`
+			Max        string `json:"max"`
+		} `json:"memory_policy"`
+		MigrationDowntime  string `json:"migration_downtime"`
+		MultiQueuesEnabled string `json:"multi_queues_enabled"`
+		RngDevice          struct {
+			Source string `json:"source"`
+		} `json:"rng_device"`
+		SmallIcon struct {
+			Href string `json:"href"`
+			ID   string `json:"id"`
+		} `json:"small_icon"`
+		SoundcardEnabled            string `json:"soundcard_enabled"`
+		StartPaused                 string `json:"start_paused"`
+		StorageErrorResumeBehaviour string `json:"storage_error_resume_behaviour"`
+		TimeZone                    struct {
+			Name string `json:"name"`
+		} `json:"time_zone"`
+		VirtioScsi struct {
+			Enabled string `json:"enabled"`
+		} `json:"virtio_scsi"`
+		CPUProfile struct {
+			Href string `json:"href"`
+			ID   string `json:"id"`
+		} `json:"cpu_profile"`
+	}
+
+	_createVM := AddVMRequest{}
+	//fmt.Println(apiJson)
+	_err := json.Unmarshal([]byte(apiJson), &_createVM)
+	if _err != nil {
+		fmt.Println("Error in VMCreation step 1: ", _err.Error())
+	}
+	addvmresponse := AddVMResponse{}
+	var body []byte
+	{
+		url := _createVM.URL
+		method := _createVM.Method
+		__json := _createVM.JSON
+		client := &http.Client{}
+		_json, _ :=json.Marshal(__json)
+		payload := strings.NewReader(string(_json))
+		//payload := __json
+		req, err := http.NewRequest(method, url, payload)
+		if err != nil {
+			fmt.Println("Error in VMCreation  step 2: ", err.Error())
+		}
+		_headers := _createVM.Headers
+		for _, v := range _headers {
+			req.Header.Add(v.Name, v.Value)
+		}
+		if err != nil {
+			fmt.Println("Error in VMCreation  step 3: ", err.Error())
+		}
+		res, err := client.Do(req)
+		defer res.Body.Close()
+		body, _ = ioutil.ReadAll(res.Body)
+	}
+	//body := runAPICall(_createVM)
+	err := json.Unmarshal(body, &addvmresponse)
+	if err != nil {
+		fmt.Println("Error in VMCreation  step 4: ", err.Error())
+	}
+	toggleTask(uuid, 0)
+	// find related VMInitialization Task
+	//ruuid := ""
+	{
+		db, err := sql.Open("mysql", MySQLUSER+":"+MySQLPASS+"@tcp(127.0.0.1:3306)/zicloud")
+		if err != nil {
+			fmt.Println("Error in VMCreation step 3: ", _err.Error())
+		}
+		//defer db.Close()
+		//results, err := db.Query("SELECT uuid as UUID ,task_apiCall as TaskAPICall , cron_expression as CronExpression , related_uuid as Ruuid, type FROM scheduler where  related_invoice=" + invoice_uuid + " and type=1")
+		//type Task struct {
+		//	UUID           string `json:"uuid"`
+		//	TaskAPICall    string `json:"taskapicall"`
+		//	Ruuid          string `json:"ruuid"`
+		//	CronExpression string `json:"cronexpression"`
+		//	Type           string `json:"type"`
+		//}
+		//for results.Next() {
+		//	var res Task
+		//	err = results.Scan(&res.UUID, &res.TaskAPICall, &res.CronExpression, &res.Ruuid, &res.Type)
+		//	ruuid = res.UUID
+		//	break
+		//}
+		//update UUID and status
+		update2, err := db.Query("update service_profile set uuid='" + addvmresponse.ID + "' , active=1 where related_invoice='" + invoice_uuid + "'")
+		update, err := db.Query("update scheduler set related_uuid='" + addvmresponse.ID + "' , active=1 where related_uuid='" + invoice_uuid + "' and type=1")
+		defer update.Close()
+		defer update2.Close()
+		//toggleTask(ruuid, 1)
+	}
+
+}
+
+func VMInitialization (relatedUuid string, apiCall string, uuid string) {
+	iaas := &ovirt{}
+	status := iaas.vmStatus(relatedUuid)
+	//fmt.Println("VM :", relatedUuid, " is now: ", status)
+	if status == "down" {
+		//fmt.Println("APICall: ", apiCall)
+		startVM := addVMTask{}
+		//b, _ := json.Marshal(apiCall)
+		_err := json.Unmarshal([]byte(apiCall), &startVM)
+		if _err != nil {
+			fmt.Println("Error in VMInitialization: ", _err.Error())
+		}
+		//fmt.Println("calling initialization for VM :", relatedUuid)
+		words := strings.Split(startVM.URL, "/")
+		//fmt.Println("Invoice : ", words[6])
+		_sha256 := sha256.Sum256([]byte(words[6]))
+		var hashChannel_ = make(chan []byte, 1)
+		hashChannel_ <- _sha256[:]
+		//fmt.Println(" startVM.JSON: ", startVM.JSON)
+		startVM.JSON = decrypt(<-hashChannel_, startVM.JSON)
+		//fmt.Println("decrypted json: ",startVM.JSON)
+		startVM.URL = OvirtURL + "/ovirt-engine/api/vms/" + relatedUuid + "/start"
+		//fmt.Println("Start URL: ", startVM.URL)
+		//fmt.Println("Initialize JSON: ", decrypt(<-hashChannel_, startVM.JSON))
+		runAPICall(startVM)
+		toggleTask(uuid, 0)
+	}
+}
+
 func vmStatistics(BA string, VMUUID string) (string, float64, float64) {
 	//ram,cpu,storage
 	var _disk []string
@@ -941,8 +1148,7 @@ func vmStatistics(BA string, VMUUID string) (string, float64, float64) {
 		//fmt.Println("Url:" ,url)
 		method := "GET"
 
-		client := &http.Client{
-		}
+		client := &http.Client{}
 		req, err := http.NewRequest(method, url, nil)
 
 		if err != nil {
@@ -958,7 +1164,7 @@ func vmStatistics(BA string, VMUUID string) (string, float64, float64) {
 		diskattachments := DiskAttachments{}
 		_err := json.Unmarshal(body, &diskattachments)
 		if _err != nil {
-			fmt.Println("Error: ", _err)
+			fmt.Println("Error in vmStatistics 1: ", _err)
 		}
 		for _, v := range diskattachments.DiskAttachment {
 			url := OvirtURL + "/ovirt-engine/api/disks/" + v.Disk.ID
@@ -1010,8 +1216,7 @@ func vmStatistics(BA string, VMUUID string) (string, float64, float64) {
 			//fmt.Println("Url:" ,url)
 			method := "GET"
 
-			client := &http.Client{
-			}
+			client := &http.Client{}
 			req, _ := http.NewRequest(method, url, nil)
 
 			//if err != nil {
@@ -1029,7 +1234,7 @@ func vmStatistics(BA string, VMUUID string) (string, float64, float64) {
 			disk := DiskAttachment{}
 			_err := json.Unmarshal(body, &disk)
 			if _err != nil {
-				fmt.Println("Error: ", _err)
+				fmt.Println("Error in vmStatistics 2 : ", _err)
 			}
 			_disk = append(_disk, disk.ProvisionedSize)
 
@@ -1041,8 +1246,7 @@ func vmStatistics(BA string, VMUUID string) (string, float64, float64) {
 	//fmt.Println("Url:" ,url)
 	method := "GET"
 
-	client := &http.Client{
-	}
+	client := &http.Client{}
 	req, err := http.NewRequest(method, url, nil)
 
 	if err != nil {
@@ -1060,7 +1264,7 @@ func vmStatistics(BA string, VMUUID string) (string, float64, float64) {
 	_vmstatistics := VMStatistics{}
 	_err := json.Unmarshal(body, &_vmstatistics)
 	if _err != nil {
-		fmt.Println("Error: ", _err)
+		fmt.Println("Error in vmStatistics 3: ", _err)
 	}
 	cpuUUID := _vmstatistics.Statistic[4].ID
 	memUsedUUID := _vmstatistics.Statistic[1].ID
@@ -1090,8 +1294,7 @@ func vmStatistics(BA string, VMUUID string) (string, float64, float64) {
 		//fmt.Println("Url:" ,url)
 		method := "GET"
 
-		client := &http.Client{
-		}
+		client := &http.Client{}
 		req, err := http.NewRequest(method, url, nil)
 
 		if err != nil {
@@ -1107,7 +1310,7 @@ func vmStatistics(BA string, VMUUID string) (string, float64, float64) {
 		cpuUsage := ItemUsage{}
 		_err := json.Unmarshal(body, &cpuUsage)
 		if _err != nil {
-			fmt.Println("Error: ", _err)
+			fmt.Println("Error in vmStatistics 4 ", _err)
 		}
 		cpu = fmt.Sprintf("%f", cpuUsage.Values.Value[0].Datum)
 	}
@@ -1116,8 +1319,7 @@ func vmStatistics(BA string, VMUUID string) (string, float64, float64) {
 		//fmt.Println("Url:" ,url)
 		method := "GET"
 
-		client := &http.Client{
-		}
+		client := &http.Client{}
 		req, err := http.NewRequest(method, url, nil)
 
 		if err != nil {
@@ -1133,7 +1335,7 @@ func vmStatistics(BA string, VMUUID string) (string, float64, float64) {
 		memUsage := ItemUsage{}
 		_err := json.Unmarshal(body, &memUsage)
 		if _err != nil {
-			fmt.Println("Error: ", _err)
+			fmt.Println("Error in vmStatistics 5: ", _err)
 		}
 		memUsed = fmt.Sprintf("%f", memUsage.Values.Value[0].Datum)
 	}
@@ -1142,8 +1344,7 @@ func vmStatistics(BA string, VMUUID string) (string, float64, float64) {
 		//fmt.Println("Url:" ,url)
 		method := "GET"
 
-		client := &http.Client{
-		}
+		client := &http.Client{}
 		req, err := http.NewRequest(method, url, nil)
 
 		if err != nil {
@@ -1159,7 +1360,7 @@ func vmStatistics(BA string, VMUUID string) (string, float64, float64) {
 		memUsage := ItemUsage{}
 		_err := json.Unmarshal(body, &memUsage)
 		if _err != nil {
-			fmt.Println("Error: ", _err)
+			fmt.Println("Error in vmStatistics 6: ", _err)
 		}
 		memTotal = fmt.Sprintf("%f", memUsage.Values.Value[0].Datum)
 	}
@@ -1171,7 +1372,7 @@ func vmStatistics(BA string, VMUUID string) (string, float64, float64) {
 	mem := _memusage / _memtotal
 
 	_cpu, _ := strconv.ParseFloat(cpu, 64)
-	return strings.Join(_disk,", "), _cpu, mem
+	return strings.Join(_disk, ", "), _cpu, mem
 
 }
 func (o ovirt) vmDetails(c echo.Context) error {
@@ -1338,8 +1539,7 @@ func (o ovirt) vmDetails(c echo.Context) error {
 	//fmt.Println("Url:" ,url)
 	method := "GET"
 
-	client := &http.Client{
-	}
+	client := &http.Client{}
 	req, _ := http.NewRequest(method, url, nil)
 
 	//if err != nil {
@@ -1357,7 +1557,7 @@ func (o ovirt) vmDetails(c echo.Context) error {
 	_vmstatus := vmStatus{}
 	_err := json.Unmarshal(body, &_vmstatus)
 	if _err != nil {
-		fmt.Println("Error: ", _err)
+		fmt.Println("Error in vmDetails : ", _err)
 	}
 	disk, cpu, ram := vmStatistics(BA, uuid)
 	type AutoGenerated struct {
@@ -1397,3 +1597,22 @@ func (o ovirt) vmDetails(c echo.Context) error {
 	return c.JSON(http.StatusOK, resp)
 	//return _vmstatus.Status, _vmstatus.Name, disk, cpu, ram
 }
+func (o ovirt) ovirtPayment(c echo.Context) error {
+	invoiceUuid :=c.FormValue("invoiceUuid")
+	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=' 1' where related_uuid='" + invoiceUuid + "' and type=0")
+	defer db.Close()
+	if err != nil {
+	}
+	defer update.Close()
+	resp := _response{
+		Origin:  "ovirt-ovirtPayment",
+		Message: "Done",
+		Code:    1000,
+	}
+	//b, _ := json.MarshalIndent(resp, "", "  ")
+	//return c.String(http.StatusOK, string(b))
+	return c.JSON(http.StatusOK, resp)
+}

+ 2 - 3
token.go

@@ -22,9 +22,9 @@ func generateTokenPair(user userInfo, cockieStr string) (map[string]string, erro
 		}
 	}
 	claims["sub"] = 1
-	claims["name"] = user.Result.Result.Givenname[0]
+	claims["name"] = user.Result.Result.UID[0]
 	claims["IPAUid"] = user.Result.Result.Uidnumber[0]
-	sha256 := sha256.Sum256([]byte(user.Result.Result.Givenname[0]))
+	sha256 := sha256.Sum256([]byte(user.Result.Result.UID[0]))
 	var hashChannel = make(chan []byte, 1)
 	hashChannel <- sha256[:]
 	claims["IPAToken"] = encrypt(<-hashChannel, cockieStr)
@@ -44,7 +44,6 @@ 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()
 
 	rt, err := refreshToken.SignedString([]byte("secret"))