Browse Source

Last Updates

torabkheslat 4 years ago
parent
commit
b5a710717e
7 changed files with 693 additions and 261 deletions
  1. 21 20
      Billing.go
  2. BIN
      ZiCloud-API
  3. 60 12
      handler.go
  4. 18 12
      main.go
  5. 571 217
      ovirt.go
  6. 7 0
      response.txt
  7. 16 0
      todo.txt

+ 21 - 20
Billing.go

@@ -4,13 +4,14 @@ import (
 	"crypto/sha256"
 	"encoding/json"
 	"fmt"
-	"github.com/dgrijalva/jwt-go"
-	"github.com/labstack/echo"
 	"io/ioutil"
 	"net/http"
 	"strconv"
 	"strings"
 	"time"
+
+	"github.com/dgrijalva/jwt-go"
+	"github.com/labstack/echo"
 )
 
 type billing struct {
@@ -78,8 +79,7 @@ func (b billing) list(c echo.Context) error {
 	url := "http://172.20.15.24/iaaSInvoices/search/findByCustomerIdEquals?customerId=" + UserUUID
 	method := "GET"
 
-	client := &http.Client{
-	}
+	client := &http.Client{}
 	req, err := http.NewRequest(method, url, nil)
 
 	if err != nil {
@@ -195,8 +195,7 @@ func (b billing) Show(c echo.Context) error {
 	InvoiceUUID := c.FormValue("InvoiceUUID")
 	url := "http://172.20.15.24/invoice/iaas/get?uuid=" + InvoiceUUID
 	method := "GET"
-	client := &http.Client{
-	}
+	client := &http.Client{}
 	req, err := http.NewRequest(method, url, nil)
 
 	if err != nil {
@@ -238,7 +237,7 @@ func (b billing) Show(c echo.Context) error {
 	return c.JSON(http.StatusOK, _InvoiceResponse)
 }
 
-func IaaSCreate(UserUUID string, period string, CPU string, memory string, storageVolume string, extraIP string, extraBW string) (CPUPrice float64, memPrice float64, StoragePrice float64, IPPrice float64, extraBWPrice float64, sum float64, InvoiceID string) {
+func IaaSCreate(UserUUID string, period string, CPU string, memory string, storageVolume string, extraIP string, extraBW string, isTransient bool, coupon int) (CPUPrice float64, memPrice float64, StoragePrice float64, IPPrice float64, extraBWPrice float64, sum float64, sumRaw float64, InvoiceID string) {
 	type CreateResponse struct {
 		CreatedAt       time.Time `json:"createdAt"`
 		UpdatedAt       time.Time `json:"updatedAt"`
@@ -258,48 +257,50 @@ func IaaSCreate(UserUUID string, period string, CPU string, memory string, stora
 		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/create"
 	method := "POST"
-	//_period, _ := strconv.Atoi(period)
+	_period, _ := strconv.Atoi(period)
 	_CPU, _ := strconv.Atoi(CPU)
 	_memory, _ := strconv.Atoi(memory)
-	//_storageVolume := 40//strconv.Atoi(storageVolume)
+	_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",
     "vCoreCount": "%d",
     "ramVolume": "%d",
-    "storageVolume": "40",
+    "storageVolume": "%d",
     "extraIPCount": "%d",
-    "extraBW": "%d"
-}`, UserUUID, 1*30, _CPU, _memory/1024/1024/1024,  _extraIP, _extraBW))
-//}`, UserUUID, _period*30, _CPU, _memory/1024/1024/1024, _storageVolume/1024/1024/1024, _extraIP, _extraBW))
+    "extraBW": "%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)
-
-	client := &http.Client{
-	}
+	client := &http.Client{}
 	req, err := http.NewRequest(method, url, payload)
 
 	if err != nil {
 		fmt.Println(err)
-		return CPUPrice, memPrice, StoragePrice, IPPrice, extraBWPrice, sum, InvoiceID
+		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, InvoiceID
+		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, InvoiceID
+		return CPUPrice, memPrice, StoragePrice, IPPrice, extraBWPrice, sum, sumRaw, InvoiceID
 	}
 	//fmt.Println(string(body))
 	//return CPUPrice, memPrice, StoragePrice, IPPrice, extraBWPrice
@@ -314,5 +315,5 @@ func IaaSCreate(UserUUID string, period string, CPU string, memory string, stora
 	extraBWPrice = _CreateResponse.ExtraBwCost
 	IPPrice = _CreateResponse.ExtraIPCost
 	StoragePrice = _CreateResponse.StorageCost
-	return CPUPrice, memPrice, StoragePrice, IPPrice, extraBWPrice, _CreateResponse.Sum, _CreateResponse.UUID
+	return CPUPrice, memPrice, StoragePrice, IPPrice, extraBWPrice, _CreateResponse.Sum, _CreateResponse.SumRaw, _CreateResponse.UUID
 }

BIN
ZiCloud-API


+ 60 - 12
handler.go

@@ -726,8 +726,11 @@ func (h *handler) verifyUser(c echo.Context) error {
 	token := cockie[0].Raw
 	defer res.Body.Close()
 	//fmt.Println(token)
+	fmt.Println(res.StatusCode)
+	fmt.Println(res)
 	if res.StatusCode == 200 {
 		user := getUserInfo(token, name)
+		fmt.Println(user)
 		if user.Result.Value != name {
 			resp := _response{
 				Origin:  "VerifyUser",
@@ -935,8 +938,14 @@ func (h *handler) ListServices(c echo.Context) error {
 	token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
 	_BA := strings.Split(token, ";")
 	BA := _BA[len(_BA)-2]
+
 	db, _ := sql.Open("mysql", MySQLUSER+":"+MySQLPASS+"@tcp(127.0.0.1:3306)/zicloud")
+	defer db.Close()
 	results, _ := db.Query("SELECT `type` as `type`, uuid as Service_uuid , active , objectName FROM service_profile where uid=" + claims["IPAUid"].(string) + " and active!='-1'")
+	paiedResult, _ := db.Query("select count(id) PaidCount from iaasinvoice where customer_id='" + login(BA).AuthenticatedUser.ID + "' and is_paid=1")
+	totalInvoiceResult, _ := db.Query("select count(id) TotalInvoiceCount from iaasinvoice where customer_id='" + login(BA).AuthenticatedUser.ID + "'")
+	PaidCount := 0
+	TotalInvoiceCount := 0
 	activeCount := 0
 	totalCount := 0
 	activeVMCount := 0
@@ -950,7 +959,7 @@ func (h *handler) ListServices(c echo.Context) error {
 		if err != nil {
 			resp := _response{
 				Origin:  "ListServices",
-				Message: "Listing Error",
+				Message: "Listing Error in service",
 				Code:    1001,
 			}
 			//b, _ := json.MarshalIndent(resp, "", "  ")
@@ -992,6 +1001,30 @@ func (h *handler) ListServices(c echo.Context) error {
 		}
 	}
 	wg.Wait()
+	for paiedResult.Next() {
+		err := paiedResult.Scan(&PaidCount)
+		if err != nil {
+			resp := _response{
+				Origin:  "ListServices",
+				Message: "Listing Error in paid",
+				Code:    1001,
+			}
+			//b, _ := json.MarshalIndent(resp, "", "  ")
+			return c.JSON(http.StatusInternalServerError, resp)
+		}
+	}
+	for totalInvoiceResult.Next() {
+		err := totalInvoiceResult.Scan(&TotalInvoiceCount)
+		if err != nil {
+			resp := _response{
+				Origin:  "ListServices",
+				Message: "Listing Error in total:" + err.Error(),
+				Code:    1001,
+			}
+			//b, _ := json.MarshalIndent(resp, "", "  ")
+			return c.JSON(http.StatusInternalServerError, resp)
+		}
+	}
 	//fmt.Println(activeVMCount)
 	//fmt.Println(activeCount)
 	//fmt.Println(totalCount)
@@ -1010,6 +1043,8 @@ func (h *handler) ListServices(c echo.Context) error {
 			TotalVMCount  string `json:"TotalVMCount"`
 			TotalCPUUsage string `json:"TotalCPUUsage"`
 			TotalMemUsage string `json:"TotalMemUsage"`
+			TotalPaid     string `json:"TotalPaid"`
+			TotalInvoice  string `json:"TotalInvoice"`
 		} `json:"message"`
 		Origin string `json:"origin"`
 		Code   int    `json:"code"`
@@ -1022,6 +1057,8 @@ func (h *handler) ListServices(c echo.Context) error {
 			TotalVMCount  string `json:"TotalVMCount"`
 			TotalCPUUsage string `json:"TotalCPUUsage"`
 			TotalMemUsage string `json:"TotalMemUsage"`
+			TotalPaid     string `json:"TotalPaid"`
+			TotalInvoice  string `json:"TotalInvoice"`
 		}{
 			TotalCount:    strconv.Itoa(totalCount),
 			ActiveCount:   strconv.Itoa(activeCount),
@@ -1029,6 +1066,8 @@ func (h *handler) ListServices(c echo.Context) error {
 			TotalVMCount:  strconv.Itoa(totalVMCount),
 			TotalCPUUsage: fmt.Sprintf("%f", 100*cpu/float64(activeVMCount)),
 			TotalMemUsage: fmt.Sprintf("%f", 100*mem/float64(activeVMCount)),
+			TotalPaid:     strconv.Itoa(PaidCount),
+			TotalInvoice:  strconv.Itoa(TotalInvoiceCount),
 		},
 		Origin: "ListServices",
 		Code:   1000,
@@ -1037,21 +1076,28 @@ 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()
+	//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))))
 	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, _ := strconv.Atoi(c.FormValue("cpu"))
-	mem, _ := strconv.Atoi(c.FormValue("mem"))
-	hdd, _ := strconv.Atoi(c.FormValue("hdd"))
-	nic, _ := strconv.Atoi(c.FormValue("nic"))
-	period, _ := strconv.Atoi(c.FormValue("period"))
+	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")
+	coupon, _ := strconv.Atoi(c.FormValue("coupon"))
 	type PriceCalculator struct {
 		Data struct {
 			TotalPrice string `json:"TotalPrice"`
@@ -1059,10 +1105,12 @@ 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)
+
 	resp := PriceCalculator{
 		Data: struct {
 			TotalPrice string `json:"TotalPrice"`
-		}{TotalPrice: strconv.Itoa((cpu*500 + mem + 10 + hdd*19 + nic*10000) * period)},
+		}{TotalPrice: strconv.Itoa(int(SUM))},
 		Origin: "PriceCalc",
 		Code:   1000,
 	}

+ 18 - 12
main.go

@@ -9,11 +9,6 @@ import (
 	"encoding/base64"
 	"encoding/json"
 	"fmt"
-	"github.com/google/uuid"
-	"github.com/jasonlvhit/gocron"
-	"github.com/labstack/echo"
-	"github.com/labstack/echo/middleware"
-	"gopkg.in/gomail.v2"
 	"io"
 	"io/ioutil"
 	"log"
@@ -22,6 +17,12 @@ import (
 	"os"
 	"strconv"
 	"strings"
+
+	"github.com/google/uuid"
+	"github.com/jasonlvhit/gocron"
+	"github.com/labstack/echo"
+	"github.com/labstack/echo/middleware"
+	"gopkg.in/gomail.v2"
 )
 
 var _appversion string = "0.1"
@@ -164,6 +165,7 @@ func main() {
 
 	iaas := &ovirt{}
 	echoHandler.GET("/ovirtListVMs", iaas.listVM, isLoggedIn)
+	echoHandler.POST("/ovirtVNC", iaas.VNC, isLoggedIn)
 	echoHandler.GET("/ovirtListTemplates", iaas.listTemplate, isLoggedIn)
 	echoHandler.POST("/ovirtAddVM", iaas.addvm, isLoggedIn)
 	echoHandler.POST("/ovirtStartVM", iaas.StartVM, isLoggedIn)
@@ -179,6 +181,7 @@ func main() {
 	echoHandler.POST("/vmHistory", iaas.vmHistory, isLoggedIn)
 	echoHandler.GET("/SSHKeyGen", iaas.SSHKeyGen, isLoggedIn)
 	echoHandler.POST("/ovirtPayment", iaas.ovirtPayment, isLoggedIn)
+	echoHandler.POST("/ovirtSuspend", iaas.ovirtSuspend, isLoggedIn)
 
 	billing := billing{}
 	echoHandler.POST("/billingList", billing.list, isLoggedIn)
@@ -193,7 +196,7 @@ func encrypt(key []byte, text string) string {
 	block, err := aes.NewCipher(key)
 	if err != nil {
 		//panic(err)
-		fmt.Sprintf("encrypt got error")
+		fmt.Println("encrypt got error")
 		return ""
 	}
 	// The IV needs to be unique, but not secure. Therefore it's common to
@@ -201,7 +204,7 @@ func encrypt(key []byte, text string) string {
 	ciphertext := make([]byte, aes.BlockSize+len(plaintext))
 	iv := ciphertext[:aes.BlockSize]
 	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
-		fmt.Sprintf("encrypt got error")
+		fmt.Println("encrypt got error")
 		return ""
 	}
 
@@ -216,7 +219,7 @@ func decrypt(key []byte, cryptoText string) string {
 	//fmt.Println("Decrypt by: ", key)
 	block, err := aes.NewCipher(key)
 	if err != nil {
-		fmt.Sprintf("decrypt got error")
+		fmt.Println("encrypt got error")
 		return ""
 		//panic(err)
 	}
@@ -224,7 +227,7 @@ func decrypt(key []byte, cryptoText string) string {
 	// The IV needs to be unique, but not secure. Therefore it's common to
 	// include it at the beginning of the ciphertext.
 	if len(ciphertext) < aes.BlockSize {
-		fmt.Sprintf("ciphertext too short")
+		fmt.Println("encrypt got error")
 		return ""
 		//panic("ciphertext too short")
 	}
@@ -243,23 +246,26 @@ func task() {
 		TaskAPICall    string `json:"taskapicall"`
 		Ruuid          string `json:"ruuid"`
 		CronExpression string `json:"cronexpression"`
+		object_active  string `json:"object_active"`
 		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")
-	results, err := db.Query("SELECT uuid as UUID ,task_apiCall as TaskAPICall , cron_expression as CronExpression , related_uuid as Ruuid, type FROM scheduler where active=1")
+	results, err := db.Query("select sch.uuid as UUID  ,task_apiCall as TaskAPICall, cron_expression as CronExpression , related_uuid as Ruuid, sch.type as type,sp.active as object_active from scheduler sch  join service_profile sp  on sp.uuid=sch.related_uuid where sch.active=1")
+	//results, err := db.Query("SELECT uuid as UUID ,task_apiCall as TaskAPICall , cron_expression as CronExpression , related_uuid as Ruuid, type FROM scheduler where active=1")
 	for results.Next() {
 		var res Task
-		err = results.Scan(&res.UUID, &res.TaskAPICall, &res.CronExpression, &res.Ruuid, &res.Type)
+		err = results.Scan(&res.UUID, &res.TaskAPICall, &res.CronExpression, &res.Ruuid, &res.Type, &res.object_active)
 		if err != nil {
 			panic(err.Error()) // proper error handling instead of panic in your app
 		}
 		taskType := 0
 		taskType, _ = strconv.Atoi(res.Type)
+		ObjAct, _ := strconv.Atoi(res.object_active)
 		fmt.Println("Running Task : ", res.UUID)
 		if taskType == 0 {
 			createVM(res.Ruuid, res.TaskAPICall, res.UUID)
-		} else if taskType == 1 {
+		} else if taskType == 1 && ObjAct != -3 {
 			VMInitialization(res.Ruuid, res.TaskAPICall, res.UUID)
 		} else if taskType == 2 {
 

+ 571 - 217
ovirt.go

@@ -4,23 +4,24 @@ import (
 	"crypto/rand"
 	"crypto/rsa"
 	"crypto/sha256"
-	"crypto/tls"
 	"crypto/x509"
 	"database/sql"
 	"encoding/json"
 	"encoding/pem"
 	"errors"
 	"fmt"
-	"github.com/dgrijalva/jwt-go"
-	_ "github.com/go-sql-driver/mysql"
-	"github.com/labstack/echo"
 	"io/ioutil"
 	mrand "math/rand"
 	"net/http"
 	"os"
+	"os/exec"
 	"strconv"
 	"strings"
 	"time"
+
+	"github.com/dgrijalva/jwt-go"
+	_ "github.com/go-sql-driver/mysql"
+	"github.com/labstack/echo"
 )
 
 type ovirt struct {
@@ -339,6 +340,15 @@ func (o ovirt) vmStatus(uuid string) string {
 	return _vmstatus.Status
 }
 func (o ovirt) addvm(c echo.Context) error {
+	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 AddVMPayment struct {
 		Data struct {
 			Price struct {
@@ -348,6 +358,7 @@ func (o ovirt) addvm(c echo.Context) error {
 				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"`
@@ -365,6 +376,7 @@ func (o ovirt) addvm(c echo.Context) error {
 	_BA := strings.Split(token, ";")
 	BA := _BA[len(_BA)-2]
 	var vmname, 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")
@@ -376,68 +388,12 @@ func (o ovirt) addvm(c echo.Context) error {
 	extraBW = c.FormValue("extraBW")
 	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"
-	//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"
-	//        }
-	//    }
-	//}
-	//`, 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,
@@ -534,7 +490,40 @@ func (o ovirt) addvm(c echo.Context) error {
 	})
 	uuid, _ := uuidgen("APIGW-Ovirt-addVMTask")
 	//invoiceUUID, _ := uuidgen("APIGW-FakeInvoice")
-	CPUPrice, memPrice, StoragePrice, IPPrice, extraBWPrice, SUM, invoiceUUID := IaaSCreate(login(BA).AuthenticatedUser.ID, period, cpuThread, mem, Disk, nic, extraBW)
+	CPUPrice, memPrice, StoragePrice, IPPrice, extraBWPrice, SUM, SUMRaw, invoiceUUID := IaaSCreate(login(BA).AuthenticatedUser.ID, period, cpuThread, mem, Disk, nic, extraBW, false, coupon)
+
+	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 := AddVMPayment{
 		Data: struct {
 			Price struct {
@@ -544,6 +533,7 @@ func (o ovirt) addvm(c echo.Context) error {
 				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"`
@@ -555,6 +545,7 @@ func (o ovirt) addvm(c echo.Context) error {
 				Nic    float64 `json:"nic"`
 				BW     float64 `json:"bw"`
 				SUM    float64 `json:"sum"`
+				SUMRaw float64 `json:"SUMRaw"`
 				Period string  `json:"period"`
 			}{
 				CPU:    CPUPrice,
@@ -563,6 +554,7 @@ func (o ovirt) addvm(c echo.Context) error {
 				Nic:    IPPrice,
 				BW:     extraBWPrice,
 				SUM:    SUM,
+				SUMRaw: SUMRaw,
 				Period: period,
 			},
 			InvoiceUUID: invoiceUUID,
@@ -580,7 +572,7 @@ func (o ovirt) addvm(c echo.Context) error {
 		b, _ := json.MarshalIndent(resp, "", "  ")
 		return c.String(http.StatusBadRequest, string(b))
 	}
-	//fmt.Println("Invoice: ",invoiceUUID)
+	fmt.Println("NewVM: ", newvm)
 	__createVM, _ := json.MarshalIndent(newvm, "", "  ")
 	// Add VM Task
 	addTask(uuid, string(__createVM), "", "APIGW", "VM Creation for "+claims["name"].(string), invoiceUUID, "0", "0")
@@ -606,6 +598,7 @@ func (o ovirt) addvm(c echo.Context) error {
 			"NOW() ," +
 			"-1" + "," +
 			"'" + vmname + "'," +
+			"'" + string(jsonDetail) + "'," +
 			"'" + invoiceUUID + "' )")
 		defer insert.Close()
 		if err != nil {
@@ -670,6 +663,7 @@ func (o ovirt) addvm(c echo.Context) error {
 		__startVM, _ := json.MarshalIndent(startVM, "", "  ")
 		//fmt.Println("StartVMHeaders: ", string(__startVMHeaders))
 		addTask(uuid, string(__startVM), "", "APIGW", "VM Initialization", invoiceUUID, "1", "0")
+
 	}
 	//resp := _response{
 	//	Origin:  "ovirt-addvm",
@@ -905,8 +899,14 @@ func (o ovirt) listVM(c echo.Context) error {
 	req.Header.Add("Authorization", BA)
 
 	res, err := client.Do(req)
+	if err != nil {
+		fmt.Println(err)
+	}
 	defer res.Body.Close()
 	body, err := ioutil.ReadAll(res.Body)
+	if err != nil {
+		fmt.Println(err)
+	}
 	//fmt.Printf("%s",body)
 	//b, _ := json.MarshalIndent(body, "", "  ")
 	_VMLists := listVMs{}
@@ -1030,8 +1030,9 @@ func (o ovirt) StartVM(c echo.Context) error {
 	addTask(uuid, string(__startVM), "", "APIGW", "VM Start", vmuuid, "1", "1")
 
 	resp := _response{
+
 		Origin:  "ovirt-StartVM",
-		Message: "Done",
+		Message: "Operation Started",
 		Code:    1000,
 	}
 	//b, _ := json.MarshalIndent(resp, "", "  ")
@@ -1048,50 +1049,42 @@ func (o ovirt) StopVM(c echo.Context) error {
 	token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
 	_BA := strings.Split(token, ";")
 	BA := _BA[len(_BA)-2]
-	url := OvirtURL + "/ovirt-engine/api/vms/" + vmuuid + "/shutdown"
-	method := "POST"
-	__json := "{\"async\":\"true\"}"
-	sha256 := sha256.Sum256([]byte(vmuuid))
-	var hashChannel = make(chan []byte, 1)
-	hashChannel <- sha256[:]
-	___json := encrypt(<-hashChannel, __json)
+	{
+		url := "https://ovirt-cl.zi-tel.com/ovirt-engine/api/vms/" + vmuuid + "/shutdown"
+		method := "POST"
 
-	payload := strings.NewReader(___json)
-	tr := &http.Transport{
-		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
-	}
-	client := &http.Client{Transport: tr}
-	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)
-	res, err := client.Do(req)
-	if err != nil {
-		//return c.String(http.StatusBadRequest, "Error"+err.Error())
-		return c.JSON(http.StatusOK, "Error"+err.Error())
-	}
-	defer res.Body.Close()
-	body, err := ioutil.ReadAll(res.Body)
-	fmt.Println("Resp:" + string(body))
+		payload := strings.NewReader(`{
+   "async":"true"
+}`)
 
-	//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")
-	//__startVM, _ := json.MarshalIndent(req, "", "  ")
-	//fmt.Println("StartVMHeaders: ", string(__startVMHeaders))
-	//addTask(uuid, string(__startVM), "", "APIGW", "VM Start", vmuuid, "1", "1")
+		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)
+		if err != nil {
+			fmt.Println(err)
+		}
+		defer res.Body.Close()
+
+		_, err = ioutil.ReadAll(res.Body)
+		if err != nil {
+			//return c.String(http.StatusBadRequest, "Error"+err.Error())
+			return c.JSON(http.StatusBadRequest, "Error"+err.Error())
+		}
+		//	fmt.Println(string(body))
+	}
 
 	resp := _response{
 		Origin:  "ovirt-StopVM",
-		Message: "Done",
+		Message: "Operation Started",
 		Code:    1000,
 	}
 	//b, _ := json.MarshalIndent(resp, "", "  ")
@@ -1108,39 +1101,40 @@ func (o ovirt) RebootVM(c echo.Context) error {
 	token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
 	_BA := strings.Split(token, ";")
 	BA := _BA[len(_BA)-2]
-	url := OvirtURL + "/ovirt-engine/api/vms/" + vmuuid + "/reboot"
-	method := "POST"
-	__json := "{\"async\":\"true\"}"
-	sha256 := sha256.Sum256([]byte(vmuuid))
-	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})
+	{
+		url := "https://ovirt-cl.zi-tel.com/ovirt-engine/api/vms/" + vmuuid + "/reboot"
+		method := "POST"
 
-	//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")
-	__startVM, _ := json.MarshalIndent(startVM, "", "  ")
-	//fmt.Println("StartVMHeaders: ", string(__startVMHeaders))
-	addTask(uuid, string(__startVM), "", "APIGW", "VM Start", vmuuid, "1", "1")
+		payload := strings.NewReader(`{
+   "async":"true"
+}`)
+
+		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)
+		if err != nil {
+			fmt.Println(err)
+		}
+		defer res.Body.Close()
+
+		_, err = ioutil.ReadAll(res.Body)
+		if err != nil {
+			//return c.String(http.StatusBadRequest, "Error"+err.Error())
+			return c.JSON(http.StatusBadRequest, "Error"+err.Error())
+		}
+	}
 	resp := _response{
 		Origin:  "ovirt-RebootVM",
-		Message: "Done",
+		Message: "Operation Started",
 		Code:    1000,
 	}
 	//b, _ := json.MarshalIndent(resp, "", "  ")
@@ -1157,7 +1151,57 @@ func (o ovirt) PowerOffVM(c echo.Context) error {
 	token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
 	_BA := strings.Split(token, ";")
 	BA := _BA[len(_BA)-2]
-	url := OvirtURL + "/ovirt-engine/api/vms/" + vmuuid + "/stop"
+	{
+		url := "https://ovirt-cl.zi-tel.com/ovirt-engine/api/vms/" + vmuuid + "/stop"
+		method := "POST"
+
+		payload := strings.NewReader(`{
+   "async":"true"
+}`)
+
+		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)
+		if err != nil {
+			fmt.Println(err)
+		}
+		defer res.Body.Close()
+
+		_, err = ioutil.ReadAll(res.Body)
+		if err != nil {
+			//return c.String(http.StatusBadRequest, "Error"+err.Error())
+			return c.JSON(http.StatusBadRequest, "Error"+err.Error())
+		}
+	}
+	resp := _response{
+		Origin:  "ovirt-RebootVM",
+		Message: "Operation Started",
+		Code:    1000,
+	}
+	//b, _ := json.MarshalIndent(resp, "", "  ")
+	//return c.String(http.StatusOK, string(b))
+	return c.JSON(http.StatusOK, resp)
+}
+func (o ovirt) ResetVM(c echo.Context) error {
+	vmuuid := c.FormValue("VmUUID")
+	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]
+	url := OvirtURL + "/ovirt-engine/api/vms/" + vmuuid + "/start"
 	method := "POST"
 	__json := "{\"async\":\"true\"}"
 	sha256 := sha256.Sum256([]byte(vmuuid))
@@ -1175,36 +1219,49 @@ func (o ovirt) PowerOffVM(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")
 	__startVM, _ := json.MarshalIndent(startVM, "", "  ")
-	//fmt.Println("StartVMHeaders: ", string(__startVMHeaders))
 	addTask(uuid, string(__startVM), "", "APIGW", "VM Start", vmuuid, "1", "1")
 
-	resp := _response{
-		Origin:  "ovirt-PowerOffVM",
-		Message: "Done",
-		Code:    1000,
+	{
+		url := "https://ovirt-cl.zi-tel.com/ovirt-engine/api/vms/" + vmuuid + "/stop"
+		method := "POST"
+
+		payload := strings.NewReader(`{
+   "async":"true"
+}`)
+
+		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)
+		if err != nil {
+			fmt.Println(err)
+		}
+		defer res.Body.Close()
+
+		_, err = ioutil.ReadAll(res.Body)
+		if err != nil {
+			//return c.String(http.StatusBadRequest, "Error"+err.Error())
+			return c.JSON(http.StatusBadRequest, "Error"+err.Error())
+		}
 	}
-	//b, _ := json.MarshalIndent(resp, "", "  ")
-	//return c.String(http.StatusOK, string(b))
-	return c.JSON(http.StatusOK, resp)
-}
-func (o ovirt) ResetVM(c echo.Context) error {
 	resp := _response{
 		Origin:  "ovirt-ResetVM",
-		Message: "not implemented",
-		Code:    1003,
+		Message: "Operation Started",
+		Code:    1000,
 	}
 	//b, _ := json.MarshalIndent(resp, "", "  ")
-	return c.JSON(http.StatusOK, resp)
 	//return c.String(http.StatusOK, string(b))
+	return c.JSON(http.StatusOK, resp)
 
 }
 func (o ovirt) AddNIC(c echo.Context) error {
@@ -1395,6 +1452,7 @@ func createVM(invoice_uuid string, apiJson string, uuid string) {
 	//fmt.Println(apiJson)
 	_err := json.Unmarshal([]byte(apiJson), &_createVM)
 	if _err != nil {
+		fmt.Println(apiJson)
 		fmt.Println("Error in VMCreation step 1: ", _err.Error())
 	}
 	addvmresponse := AddVMResponse{}
@@ -1407,6 +1465,9 @@ func createVM(invoice_uuid string, apiJson string, uuid string) {
 		_json, _ := json.Marshal(__json)
 		payload := strings.NewReader(string(_json))
 		//payload := __json
+		fmt.Println("First unmarshal", string(_json))
+
+		fmt.Println("second unmarshal", __json.Description)
 		req, err := http.NewRequest(method, url, payload)
 		if err != nil {
 			fmt.Println("Error in VMCreation  step 2: ", err.Error())
@@ -1419,6 +1480,9 @@ func createVM(invoice_uuid string, apiJson string, uuid string) {
 			fmt.Println("Error in VMCreation  step 3: ", err.Error())
 		}
 		res, err := client.Do(req)
+		if err != nil {
+			fmt.Println("Error in VMCreation  step 3.5: ", err.Error())
+		}
 		defer res.Body.Close()
 		body, _ = ioutil.ReadAll(res.Body)
 	}
@@ -1435,23 +1499,7 @@ func createVM(invoice_uuid string, apiJson string, uuid string) {
 		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 + "'")
+		update2, err := db.Query("update service_profile set uuid='" + addvmresponse.ID + "' , modification_date=NOW() , 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()
@@ -1465,7 +1513,7 @@ func VMInitialization(relatedUuid string, apiCall string, uuid string) {
 	//fmt.Println("VM :", relatedUuid)
 	status := iaas.vmStatus(relatedUuid)
 	fmt.Println("VM :", relatedUuid, " is now: ", status)
-	if status == "down" {
+	if status == "down" || status == "suspended" {
 		//fmt.Println("APICall: ", apiCall)
 		startVM := addVMTask{}
 		//b, _ := json.Marshal(apiCall)
@@ -1530,8 +1578,8 @@ 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()
 		diskattachments := DiskAttachments{}
 		_err := json.Unmarshal(body, &diskattachments)
 		if _err != nil {
@@ -1598,7 +1646,6 @@ func vmStatistics(BA string, VMUUID string) (string, float64, float64, error) {
 			req.Header.Add("Authorization", BA)
 
 			res, _ := client.Do(req)
-			defer res.Body.Close()
 			body, _ := ioutil.ReadAll(res.Body)
 
 			//fmt.Println("full response: ",string(body))
@@ -1607,6 +1654,7 @@ func vmStatistics(BA string, VMUUID string) (string, float64, float64, error) {
 			if _err != nil {
 				fmt.Println("Error in vmStatistics 2 : ", _err)
 			}
+			defer res.Body.Close()
 			_disk = append(_disk, disk.ProvisionedSize)
 
 			//_disk = D_disk + "" + disk.ProvisionedSize+" "
@@ -1628,12 +1676,12 @@ 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)
 	fmt.Println("Code: ", res.StatusCode)
 	if err != nil || res.StatusCode == 404 {
 		return "", -1, -1, errors.New("unexpected Error")
 	}
+	defer res.Body.Close()
 	//fmt.Println("full response: ", string(body))
 	_vmstatistics := VMStatistics{}
 	_err := json.Unmarshal(body, &_vmstatistics)
@@ -1924,7 +1972,6 @@ func (o ovirt) vmDetails(c echo.Context) error {
 	req.Header.Add("Authorization", BA)
 
 	res, _ := client.Do(req)
-	defer res.Body.Close()
 	body, _ := ioutil.ReadAll(res.Body)
 
 	//fmt.Println("full response: ",string(body))
@@ -1938,46 +1985,84 @@ func (o ovirt) vmDetails(c echo.Context) error {
 		}
 		return c.JSON(http.StatusNotFound, resp)
 	}
-	disk, cpu, ram, err := vmStatistics(BA, uuid)
-	if err != nil {
-		fmt.Println("Error in vmDetails 2 : ", err)
-		resp := _response{
-			Origin:  "vmDetails",
-			Message: "Unexpected Error",
-			Code:    1001,
+
+	defer res.Body.Close()
+	//	disk, cpu, ram, err := vmStatistics(BA, uuid)
+	cpuCore, _ := strconv.Atoi(_vmstatus.CPU.Topology.Cores)
+	cpuThread, _ := strconv.Atoi(_vmstatus.CPU.Topology.Threads)
+	cpuSocket, _ := strconv.Atoi(_vmstatus.CPU.Topology.Sockets)
+	cpu := cpuThread * cpuCore * cpuSocket
+	ram, _ := strconv.Atoi(_vmstatus.Memory)
+	diskStruct := listDisks(uuid, BA)
+	disk := 0
+	_size := 0
+	for _, v := range diskStruct {
+		_size, _ = strconv.Atoi(v.TotalSize)
+	}
+	disk += _size
+	nicStruct := listNIC(uuid, BA)
+	nic := len(nicStruct)
+
+	type JSONDetails struct {
+		Name  string `json:"name"`
+		Value string `json:"value"`
+		Type  string `json:"type"`
+	}
+	vmJsonDetails := [8]JSONDetails{}
+	{
+		db, err := sql.Open("mysql", MySQLUSER+":"+MySQLPASS+"@tcp(127.0.0.1:3306)/zicloud")
+		if err != nil {
+			resp := _response{
+				Origin:  "vmDetails",
+				Message: "Not Found",
+				Code:    1001,
+			}
+			return c.JSON(http.StatusNotFound, resp)
 		}
-		return c.JSON(http.StatusInternalServerError, resp)
+		defer db.Close()
+		results, err := db.Query("select details from service_profile where uuid='" + uuid + "'")
+		//results, err := db.Query("SELECT uuid as UUID ,task_apiCall as TaskAPICall , cron_expression as CronExpression , related_uuid as Ruuid, type FROM scheduler where active=1")
+		detailsStr := ""
+		for results.Next() {
+			_ = results.Scan(&detailsStr)
+		}
+		json.Unmarshal([]byte(detailsStr), &vmJsonDetails)
 	}
+
 	type AutoGenerated struct {
 		Message struct {
-			Disk       string `json:"Disk"`
-			Memory     string `json:"Memory"`
-			CPU        string `json:"CPU"`
-			NetAddress string `json:"NetAddress"`
-			Traffic    string `json:"Traffic"`
-			Status     string `json:"Status"`
-			Name       string `json:"Name"`
+			Disk     string `json:"Disk"`
+			Memory   string `json:"Memory"`
+			CPU      string `json:"CPU"`
+			NIC      string `json:"NIC"`
+			Traffic  string `json:"Traffic"`
+			Status   string `json:"Status"`
+			Name     string `json:"Name"`
+			Template string `json:"Template"`
 		} `json:"message"`
 		Origin string `json:"origin"`
 		Code   int    `json:"code"`
 	}
 	resp := AutoGenerated{
 		Message: struct {
-			Disk       string `json:"Disk"`
-			Memory     string `json:"Memory"`
-			CPU        string `json:"CPU"`
-			NetAddress string `json:"NetAddress"`
-			Traffic    string `json:"Traffic"`
-			Status     string `json:"Status"`
-			Name       string `json:"Name"`
+			Disk     string `json:"Disk"`
+			Memory   string `json:"Memory"`
+			CPU      string `json:"CPU"`
+			NIC      string `json:"NIC"`
+			Traffic  string `json:"Traffic"`
+			Status   string `json:"Status"`
+			Name     string `json:"Name"`
+			Template string `json:"Template"`
 		}{
-			Disk:       disk,
-			Memory:     fmt.Sprintf("%f", ram),
-			CPU:        fmt.Sprintf("%f", cpu),
-			NetAddress: "",
-			Traffic:    "",
-			Status:     _vmstatus.Status,
-			Name:       _vmstatus.Name,
+			Disk:    fmt.Sprintf("%d", disk),
+			Memory:  fmt.Sprintf("%d", ram),
+			CPU:     fmt.Sprintf("%d", cpu),
+			NIC:     fmt.Sprintf("%d", nic),
+			Traffic: vmJsonDetails[5].Value,
+			Status:  _vmstatus.Status,
+			// v.Name[len(login(BA).AuthenticatedUser.ID)+3:]
+			Name:     _vmstatus.Name[len(login(BA).AuthenticatedUser.ID)+3:],
+			Template: vmJsonDetails[7].Value,
 		},
 		Origin: "vmDetails",
 		Code:   1000,
@@ -2082,8 +2167,7 @@ func listNIC(VMUUID string, BA string) []struct {
 	method := "GET"
 
 	payload := strings.NewReader(``)
-	client := &http.Client{
-	}
+	client := &http.Client{}
 	req, err := http.NewRequest(method, url, payload)
 
 	if err != nil {
@@ -2130,14 +2214,25 @@ func listNIC(VMUUID string, BA string) []struct {
 	}{}
 	for _, i := range _VMNIC.Nic {
 		x.IPv4 = "1.1.1.1"
-		///TODO:GetAssignedIP
+		///TODO:GetAssignedIP from DHCP Table and remove this block
 		x.IPv6 = "Null"
 		x.Mac = i.Mac.Address
-		x.ReportedDevices.Mac = i.ReportedDevices.ReportedDevice[0].Mac.Address
-		x.ReportedDevices.IPv4 = i.ReportedDevices.ReportedDevice[0].Ips.IP[0].Address
-		x.ReportedDevices.IPv6 = i.ReportedDevices.ReportedDevice[0].Ips.IP[1].Address
+		if len(i.ReportedDevices.ReportedDevice) > 0 {
+			x.ReportedDevices.Mac = i.ReportedDevices.ReportedDevice[0].Mac.Address
+			if len(i.ReportedDevices.ReportedDevice[0].Ips.IP) > 1 {
+				x.ReportedDevices.IPv4 = i.ReportedDevices.ReportedDevice[0].Ips.IP[0].Address
+				x.ReportedDevices.IPv6 = i.ReportedDevices.ReportedDevice[0].Ips.IP[1].Address
+
+			}
+		} else {
+			x.ReportedDevices.Mac = ""
+			x.ReportedDevices.IPv4 = ""
+			x.ReportedDevices.IPv6 = ""
+
+		}
 		_Data = append(_Data, x)
 	}
+
 	_NICList.NIC = _Data
 	return _NICList.NIC
 }
@@ -2180,8 +2275,7 @@ func listDisks(VMUUID string, ba string) []struct {
 
 	payload := strings.NewReader(``)
 
-	client := &http.Client{
-	}
+	client := &http.Client{}
 	req, err := http.NewRequest(method, url, payload)
 
 	if err != nil {
@@ -2277,8 +2371,7 @@ func DiskDetails(id string, ba string) struct {
 
 	payload := strings.NewReader(``)
 
-	client := &http.Client{
-	}
+	client := &http.Client{}
 	req, err := http.NewRequest(method, url, payload)
 
 	if err != nil {
@@ -2311,12 +2404,100 @@ func DiskDetails(id string, ba string) struct {
 		ActualSize string `json:"ActualSize"`
 	}{
 		Name:       _DiskDetail.Alias,
-		TotalSize:  _DiskDetail.TotalSize,
+		TotalSize:  _DiskDetail.ProvisionedSize,
 		ActualSize: _DiskDetail.ActualSize,
 	}
 
 	return Disk
 }
+func (o ovirt) VNC(c echo.Context) error {
+	type graphicConsoleList struct {
+		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"`
+		} `json:"graphics_console"`
+	}
+
+	type vnc struct {
+		RemoteViewerConnectionFile string `json:"remote_viewer_connection_file"`
+	}
+	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]
+	vmuuid := c.FormValue("VmUUID")
+	urlgraphiclist := OvirtURL + "/ovirt-engine/api/vms/" + vmuuid + "/graphicsconsoles"
+	client := &http.Client{}
+	req, err := http.NewRequest("Get", urlgraphiclist, nil)
+	if err != nil {
+		fmt.Println(err)
+	}
+	req.Header.Add("Version", "4")
+	req.Header.Add("Accept", "application/json")
+	req.Header.Add("Authorization", BA)
+
+	res, err := client.Do(req)
+	body, err := ioutil.ReadAll(res.Body)
+	defer res.Body.Close()
+	_graphicConsoleList := graphicConsoleList{}
+	err = json.Unmarshal(body, &_graphicConsoleList)
+	urlvncfile := OvirtURL + "/ovirt-engine/api/vms/" + vmuuid + "/graphicsconsoles/" + _graphicConsoleList.GraphicsConsole[0].ID + "/remoteviewerconnectionfile"
+	client2 := &http.Client{}
+	payload := strings.NewReader(`{
+}`)
+
+	req2, err := http.NewRequest("POST", urlvncfile, payload)
+
+	req2.Header.Add("Version", "4")
+	req2.Header.Add("Accept", "application/json")
+	req2.Header.Add("Content-Type", "application/json")
+	req2.Header.Add("Authorization", BA)
+
+	res2, err := client2.Do(req2)
+	body2, err := ioutil.ReadAll(res2.Body)
+	_vnc := vnc{}
+	err = json.Unmarshal(body2, &_vnc)
+	defer res2.Body.Close()
+	result := _vnc.RemoteViewerConnectionFile
+	dhost := strings.Split(result, "\n")[2]
+	dport := strings.Split(result, "\n")[3]
+	password := strings.Split(result, "\n")[4]
+	mrand.Seed(time.Now().UTC().UnixNano())
+	randInt := func(min, max int) int {
+		return min + mrand.Intn(max-min)
+	}
+	lport := randInt(5800, 6000)
+	{
+
+		app := "/root/novncRunner"
+		arg0 := fmt.Sprintf("%d", lport)
+		arg1 := strings.Split(dhost, "=")
+		arg2 := strings.Split(dport, "=")
+		exec.Command(app, arg2[1], arg1[1], arg0).Output()
+	}
+
+	resp := _response{
+		Origin:  "ovirt-VNC",
+		Message: "http://zi-cloud.ir:" + fmt.Sprintf("%d", lport) + "/vnc.html?autoconnect=true&password=" + strings.Split(password, "=")[1],
+		Code:    1000,
+	}
+	return c.JSON(http.StatusOK, resp)
+}
 func (o ovirt) listTemplate(c echo.Context) error {
 	type templateList struct {
 		Template []struct {
@@ -2475,8 +2656,8 @@ func (o ovirt) listTemplate(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()
 	_templateList := templateList{}
 	err = json.Unmarshal(body, &_templateList)
 	//fmt.Println("resp:",string(body))
@@ -2607,7 +2788,7 @@ func (o ovirt) SSHKeyGen(c echo.Context) error {
 	}
 	user := c.Get("user").(*jwt.Token)
 	claims := user.Claims.(jwt.MapClaims)
-	email:=fmt.Sprintf("%s",claims["mail"])
+	email := fmt.Sprintf("%s", claims["mail"])
 	fmt.Println(email)
 
 	mrand.Seed(time.Now().Unix())
@@ -2678,3 +2859,176 @@ func (o ovirt) SSHKeyGen(c echo.Context) error {
 	}
 	return c.JSON(http.StatusOK, _SSHKeyGenResponse)
 }
+
+func (o ovirt) ovirtSuspend(c echo.Context) error {
+	type VMSuspend struct {
+		Async string `json:"async"`
+		Job   struct {
+			Href string `json:"href"`
+			ID   string `json:"id"`
+		} `json:"job"`
+		Status string `json:"status"`
+		Href   string `json:"href"`
+		ID     string `json:"id"`
+		Link   []struct {
+			Href string `json:"href"`
+			Rel  string `json:"rel"`
+		} `json:"link"`
+	}
+
+	vmuuid := c.FormValue("VmUUID")
+	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]
+	url := OvirtURL + "/ovirt-engine/api/vms/" + vmuuid + "/suspend"
+	method := "POST"
+
+	payload := strings.NewReader(`{
+		   "async":"true"
+		}`)
+
+	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")
+	///TODO: BA
+	req.Header.Add("Authorization", BA)
+	req.Header.Add("Content-Type", "application/json")
+
+	res, err := client.Do(req)
+
+	if err != nil {
+		fmt.Println("Error 1", err)
+	}
+	defer res.Body.Close()
+
+	body, err := ioutil.ReadAll(res.Body)
+	//fmt.Println(res.Status)
+	//fmt.Println(res.Body)
+	if err != nil {
+		//fmt.Println("Error 3", err)
+		fmt.Println(err)
+	}
+	_VMSuspend := VMSuspend{}
+	err = json.Unmarshal(body, &_VMSuspend)
+	if err != nil {
+		//fmt.Println("Error 4", err)
+		fmt.Println(err)
+	}
+	//fmt.Println(_VMSuspend)
+	db, err := sql.Open("mysql", MySQLUSER+":"+MySQLPASS+"@tcp(127.0.0.1:3306)/zicloud")
+	if err != nil {
+	}
+	update, err := db.Query("update service_profile set active='-2' where uuid='" + vmuuid + "'")
+	defer db.Close()
+	if err != nil {
+	}
+	defer update.Close()
+	type VMSuspendResponse struct {
+		Message string `json:"message"`
+		Origin  string `json:"origin"`
+		Code    int    `json:"code"`
+	}
+	resp := VMSuspendResponse{
+		Message: "Done",
+		Origin:  "ovirtSuspend",
+		Code:    1000,
+	}
+	return c.JSON(http.StatusOK, resp)
+}
+
+func (o ovirt) BillingSuspend(c echo.Context) error {
+	type VMSuspend struct {
+		Async string `json:"async"`
+		Job   struct {
+			Href string `json:"href"`
+			ID   string `json:"id"`
+		} `json:"job"`
+		Status string `json:"status"`
+		Href   string `json:"href"`
+		ID     string `json:"id"`
+		Link   []struct {
+			Href string `json:"href"`
+			Rel  string `json:"rel"`
+		} `json:"link"`
+	}
+
+	vmuuid := c.FormValue("VmUUID")
+	//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]
+	url := OvirtURL + "/ovirt-engine/api/vms/" + vmuuid + "/suspend"
+	method := "POST"
+
+	payload := strings.NewReader(`{
+		   "async":"true"
+		}`)
+
+	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")
+	///TODO: BA
+	req.Header.Add("Authorization", "Basic YWRtaW5AaW50ZXJuYWw6a2VsYW5zaCBqMw==")
+	req.Header.Add("Content-Type", "application/json")
+
+	res, err := client.Do(req)
+
+	if err != nil {
+		fmt.Println("Error 1", err)
+	}
+	defer res.Body.Close()
+
+	body, err := ioutil.ReadAll(res.Body)
+	//fmt.Println(res.Status)
+	//fmt.Println(res.Body)
+	if err != nil {
+		//fmt.Println("Error 3", err)
+		fmt.Println(err)
+	}
+	_VMSuspend := VMSuspend{}
+	err = json.Unmarshal(body, &_VMSuspend)
+	if err != nil {
+		//fmt.Println("Error 4", err)
+		fmt.Println(err)
+	}
+	//fmt.Println(_VMSuspend)
+	db, err := sql.Open("mysql", MySQLUSER+":"+MySQLPASS+"@tcp(127.0.0.1:3306)/zicloud")
+	if err != nil {
+	}
+	///TODO: Sanitize Input variables
+	update, err := db.Query("update service_profile set active='-3' where uuid='" + vmuuid + "'")
+	defer db.Close()
+	if err != nil {
+	}
+	defer update.Close()
+	type VMSuspendResponse struct {
+		Message string `json:"message"`
+		Origin  string `json:"origin"`
+		Code    int    `json:"code"`
+	}
+	resp := VMSuspendResponse{
+		Message: "Done",
+		Origin:  "ovirtSuspend",
+		Code:    1000,
+	}
+	return c.JSON(http.StatusOK, resp)
+}

+ 7 - 0
response.txt

@@ -0,0 +1,7 @@
+1001: function retured error
+1002: user found in Verify User
+1003: duplicate active resetLink
+1003: not implemented
+1004:
+
+

+ 16 - 0
todo.txt

@@ -0,0 +1,16 @@
+1: encrypt decrypt error handleing
+2: Mysql ORM gorm.io/gorm
+3: audit all activities
+4: scheduler confilict with user credential changes
+5: explicit define syntax of insert queries (names() values())
+6: try final method for sql queries
+7: **VM STATUS CHECK BY admin@internal **
+8: move user/passwords and other configs to config files
+9: add a working flag to schedule table to avoid multiple occurance
+10: reregister failed users
+11: verify payment duplication before confirm
+12: weak password on registration
+13: vmname duplication
+14: list vm-templates to show in add-vm
+15: actions and vnc
+16: find a way to store NationalID