ovirt.go 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666
  1. package main
  2. import (
  3. "crypto/sha256"
  4. "database/sql"
  5. "encoding/json"
  6. "fmt"
  7. "github.com/dgrijalva/jwt-go"
  8. _ "github.com/go-sql-driver/mysql"
  9. "github.com/labstack/echo"
  10. "io/ioutil"
  11. "net/http"
  12. "strconv"
  13. "strings"
  14. )
  15. type ovirt struct {
  16. }
  17. var MySQLUSER = "apigw"
  18. var MySQLPASS = "^_P+^7Q$bmPj+$xB"
  19. func login(BA string) OvirtObject {
  20. url := OvirtURL + "/ovirt-engine/api"
  21. method := "GET"
  22. client := &http.Client{}
  23. req, err := http.NewRequest(method, url, nil)
  24. if err != nil {
  25. fmt.Println(err)
  26. }
  27. req.Header.Add("Version", "4")
  28. req.Header.Add("Accept", "application/json")
  29. req.Header.Add("Authorization", BA)
  30. res, err := client.Do(req)
  31. defer res.Body.Close()
  32. body, err := ioutil.ReadAll(res.Body)
  33. object := OvirtObject{}
  34. err = json.Unmarshal(body, &object)
  35. return object
  36. }
  37. type OvirtObject struct {
  38. ProductInfo struct {
  39. Name string `json:"name"`
  40. Version struct {
  41. Build string `json:"build"`
  42. FullVersion string `json:"full_version"`
  43. Major string `json:"major"`
  44. Minor string `json:"minor"`
  45. Revision string `json:"revision"`
  46. } `json:"version"`
  47. } `json:"product_info"`
  48. SpecialObjects struct {
  49. BlankTemplate struct {
  50. Href string `json:"href"`
  51. ID string `json:"id"`
  52. } `json:"blank_template"`
  53. RootTag struct {
  54. Href string `json:"href"`
  55. ID string `json:"id"`
  56. } `json:"root_tag"`
  57. } `json:"special_objects"`
  58. Time int64 `json:"time"`
  59. AuthenticatedUser struct {
  60. Href string `json:"href"`
  61. ID string `json:"id"`
  62. } `json:"authenticated_user"`
  63. EffectiveUser struct {
  64. Href string `json:"href"`
  65. ID string `json:"id"`
  66. } `json:"effective_user"`
  67. Link []struct {
  68. Href string `json:"href"`
  69. Rel string `json:"rel"`
  70. } `json:"link"`
  71. }
  72. type TaskHeader struct {
  73. Name string `json:"Name,omitempty"`
  74. Value string `json:"Value,omitempty"`
  75. }
  76. type addVMTask struct {
  77. URL string `json:"url"`
  78. JSON string `json:__json`
  79. Method string `json:"method"`
  80. Headers []struct {
  81. Name string `json:"Name,omitempty"`
  82. Value string `json:"Value,omitempty"`
  83. } `json:"headers"`
  84. }
  85. type AddVMRequest struct {
  86. URL string `json:"url"`
  87. JSON struct {
  88. Name string `json:"name"`
  89. Description string `json:"description"`
  90. Comment string `json:"comment"`
  91. Cluster struct {
  92. Name string `json:"name"`
  93. } `json:"cluster"`
  94. Template struct {
  95. Name string `json:"name"`
  96. } `json:"template"`
  97. CPU struct {
  98. Topology struct {
  99. Sockets string `json:"sockets"`
  100. Cores string `json:"cores"`
  101. Threads string `json:"threads"`
  102. } `json:"topology"`
  103. } `json:"cpu"`
  104. Memory string `json:"memory"`
  105. MemoryPolicy struct {
  106. Ballooning string `json:"ballooning"`
  107. Guaranteed string `json:"guaranteed"`
  108. OverCommit struct {
  109. Percent string `json:"percent"`
  110. } `json:"over_commit"`
  111. } `json:"memory_policy"`
  112. } `json:"JSON"`
  113. Method string `json:"method"`
  114. Headers []struct {
  115. Name string `json:"Name"`
  116. Value string `json:"Value"`
  117. } `json:"headers"`
  118. }
  119. type VMStatistics struct {
  120. Statistic []struct {
  121. Kind string `json:"kind"`
  122. Type string `json:"type"`
  123. Unit string `json:"unit"`
  124. Values struct {
  125. Value []struct {
  126. Datum float64 `json:"datum"`
  127. } `json:"value"`
  128. } `json:"values"`
  129. VM struct {
  130. Href string `json:"href"`
  131. ID string `json:"id"`
  132. } `json:"vm,omitempty"`
  133. Name string `json:"name"`
  134. Description string `json:"description"`
  135. Href string `json:"href,omitempty"`
  136. ID string `json:"id"`
  137. } `json:"statistic"`
  138. }
  139. func (o ovirt) vmStatus(uuid string) string {
  140. type vmStatus struct {
  141. NextRunConfigurationExists string `json:"next_run_configuration_exists"`
  142. NumaTuneMode string `json:"numa_tune_mode"`
  143. Status string `json:"status"`
  144. StopTime int64 `json:"stop_time"`
  145. OriginalTemplate struct {
  146. Href string `json:"href"`
  147. ID string `json:"id"`
  148. } `json:"original_template"`
  149. Template struct {
  150. Href string `json:"href"`
  151. ID string `json:"id"`
  152. } `json:"template"`
  153. Actions struct {
  154. Link []struct {
  155. Href string `json:"href"`
  156. Rel string `json:"rel"`
  157. } `json:"link"`
  158. } `json:"actions"`
  159. Name string `json:"name"`
  160. Description string `json:"description"`
  161. Comment string `json:"comment"`
  162. Href string `json:"href"`
  163. ID string `json:"id"`
  164. Bios struct {
  165. BootMenu struct {
  166. Enabled string `json:"enabled"`
  167. } `json:"boot_menu"`
  168. Type string `json:"type"`
  169. } `json:"bios"`
  170. CPU struct {
  171. Architecture string `json:"architecture"`
  172. Topology struct {
  173. Cores string `json:"cores"`
  174. Sockets string `json:"sockets"`
  175. Threads string `json:"threads"`
  176. } `json:"topology"`
  177. } `json:"cpu"`
  178. Display struct {
  179. AllowOverride string `json:"allow_override"`
  180. CopyPasteEnabled string `json:"copy_paste_enabled"`
  181. DisconnectAction string `json:"disconnect_action"`
  182. FileTransferEnabled string `json:"file_transfer_enabled"`
  183. Monitors string `json:"monitors"`
  184. SingleQxlPci string `json:"single_qxl_pci"`
  185. SmartcardEnabled string `json:"smartcard_enabled"`
  186. Type string `json:"type"`
  187. } `json:"display"`
  188. Initialization struct {
  189. AuthorizedSSHKeys string `json:"authorized_ssh_keys"`
  190. CloudInitNetworkProtocol string `json:"cloud_init_network_protocol"`
  191. CustomScript string `json:"custom_script"`
  192. HostName string `json:"host_name"`
  193. NicConfigurations struct {
  194. } `json:"nic_configurations"`
  195. RegenerateSSHKeys string `json:"regenerate_ssh_keys"`
  196. UserName string `json:"user_name"`
  197. } `json:"initialization"`
  198. Io struct {
  199. Threads string `json:"threads"`
  200. } `json:"io"`
  201. Memory string `json:"memory"`
  202. Migration struct {
  203. AutoConverge string `json:"auto_converge"`
  204. Compressed string `json:"compressed"`
  205. Encrypted string `json:"encrypted"`
  206. } `json:"migration"`
  207. Origin string `json:"origin"`
  208. Os struct {
  209. Boot struct {
  210. Devices struct {
  211. Device []string `json:"device"`
  212. } `json:"devices"`
  213. } `json:"boot"`
  214. Type string `json:"type"`
  215. } `json:"os"`
  216. Sso struct {
  217. Methods struct {
  218. Method []struct {
  219. ID string `json:"id"`
  220. } `json:"method"`
  221. } `json:"methods"`
  222. } `json:"sso"`
  223. Stateless string `json:"stateless"`
  224. Type string `json:"type"`
  225. Usb struct {
  226. Enabled string `json:"enabled"`
  227. } `json:"usb"`
  228. Cluster struct {
  229. Href string `json:"href"`
  230. ID string `json:"id"`
  231. } `json:"cluster"`
  232. Quota struct {
  233. ID string `json:"id"`
  234. } `json:"quota"`
  235. Link []struct {
  236. Href string `json:"href"`
  237. Rel string `json:"rel"`
  238. } `json:"link"`
  239. CPUShares string `json:"cpu_shares"`
  240. CreationTime int64 `json:"creation_time"`
  241. DeleteProtected string `json:"delete_protected"`
  242. HighAvailability struct {
  243. Enabled string `json:"enabled"`
  244. Priority string `json:"priority"`
  245. } `json:"high_availability"`
  246. LargeIcon struct {
  247. Href string `json:"href"`
  248. ID string `json:"id"`
  249. } `json:"large_icon"`
  250. MemoryPolicy struct {
  251. Ballooning string `json:"ballooning"`
  252. Guaranteed string `json:"guaranteed"`
  253. Max string `json:"max"`
  254. } `json:"memory_policy"`
  255. MigrationDowntime string `json:"migration_downtime"`
  256. MultiQueuesEnabled string `json:"multi_queues_enabled"`
  257. PlacementPolicy struct {
  258. Affinity string `json:"affinity"`
  259. Hosts struct {
  260. Host []struct {
  261. Href string `json:"href"`
  262. ID string `json:"id"`
  263. } `json:"host"`
  264. } `json:"hosts"`
  265. } `json:"placement_policy"`
  266. SmallIcon struct {
  267. Href string `json:"href"`
  268. ID string `json:"id"`
  269. } `json:"small_icon"`
  270. StartPaused string `json:"start_paused"`
  271. StorageErrorResumeBehaviour string `json:"storage_error_resume_behaviour"`
  272. TimeZone struct {
  273. Name string `json:"name"`
  274. } `json:"time_zone"`
  275. CPUProfile struct {
  276. Href string `json:"href"`
  277. ID string `json:"id"`
  278. } `json:"cpu_profile"`
  279. }
  280. //url := "https://ovirt-cl.zi-tel.com/ovirt-engine/api/vms/c1a44128-6c6c-406b-99d8-4a68a99380c9"
  281. url := OvirtURL + "/ovirt-engine/api/vms/" + uuid
  282. //fmt.Println("VMSTATUS UUID:" ,uuid)
  283. method := "GET"
  284. client := &http.Client{}
  285. req, err := http.NewRequest(method, url, nil)
  286. if err != nil {
  287. return "Null"
  288. }
  289. req.Header.Add("Version", "4")
  290. req.Header.Add("Accept", "application/json")
  291. //TODO: replace BA
  292. req.Header.Add("Authorization", "Basic YWRtaW5AaW50ZXJuYWw6a2VsYW5zaCBqMw==")
  293. res, err := client.Do(req)
  294. defer res.Body.Close()
  295. body, err := ioutil.ReadAll(res.Body)
  296. //fmt.Println("full response: ",string(body))
  297. _vmstatus := vmStatus{}
  298. _err := json.Unmarshal(body, &_vmstatus)
  299. if _err != nil {
  300. fmt.Println("Error in vmStatus ", _err)
  301. }
  302. return _vmstatus.Status
  303. }
  304. func (o ovirt) addvm(c echo.Context) error {
  305. type AddVMPayment struct {
  306. Data struct {
  307. Price struct {
  308. CPU string `json:"cpu"`
  309. Mem string `json:"mem"`
  310. Disk string `json:"disk"`
  311. Nic string `json:"nic"`
  312. Period string `json:"period"`
  313. } `json:"price"`
  314. InvoiceUUID string `json:"invoiceUUID"`
  315. } `json:"data"`
  316. Message string `json:"message"`
  317. Origin string `json:"origin"`
  318. Code int `json:"code"`
  319. }
  320. user := c.Get("user").(*jwt.Token)
  321. claims := user.Claims.(jwt.MapClaims)
  322. _sha256 := sha256.Sum256([]byte(string(claims["name"].(string))))
  323. var hashChannel_ = make(chan []byte, 1)
  324. hashChannel_ <- _sha256[:]
  325. token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
  326. _BA := strings.Split(token, ";")
  327. BA := _BA[len(_BA)-2]
  328. var vmname, vmdescr, vmcomment, templatename, cpuSock, cpuCore, cpuThread, mem, Disk, nic, period string
  329. vmname = c.FormValue("VmName")
  330. vmdescr = c.FormValue("VmDescr")
  331. vmcomment = c.FormValue("VmComment")
  332. templatename = c.FormValue("VmTempl")
  333. cpuThread = c.FormValue("VmCPU")
  334. Disk = c.FormValue("VmDisk")
  335. period = c.FormValue("VmPeriod")
  336. nic = c.FormValue("VmNIC")
  337. sshKey := c.FormValue("sshKey")
  338. rootpass := c.FormValue("rootpass")
  339. cpuCore = "1"
  340. cpuSock = "1"
  341. mem = c.FormValue("VmMem")
  342. url := OvirtURL + "/ovirt-engine/api/vms"
  343. method := "POST"
  344. //TODO: Encrypt this Json
  345. // _json := fmt.Sprintf(`
  346. //{
  347. // "name": "%s",
  348. // "description": "%s",
  349. // "comment": "%s",
  350. // "cluster": {
  351. // "name": "Default"
  352. // },
  353. // "template": {
  354. // "name": "%s"
  355. // },
  356. // "cpu": {
  357. // "topology": {
  358. // "sockets": "%s",
  359. // "cores": "%s",
  360. // "threads": "%s"
  361. // }
  362. // },
  363. // "memory": "%s",
  364. // "memory_policy": {
  365. // "ballooning": "true",
  366. // "guaranteed": "%s",
  367. // "over_commit": {
  368. // "percent": "10"
  369. // }
  370. // }
  371. //}
  372. //`, vmname, vmdescr, vmcomment, templatename, cpuSock, cpuCore, cpuThread, mem, mem)
  373. // Change as task
  374. //change to task// payload := strings.NewReader(_json)
  375. //change to task// //tr := &http.Transport{
  376. //change to task// // TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  377. //change to task// //}
  378. //change to task// client := &http.Client{}
  379. //change to task// req, err := http.NewRequest(method, url, payload)
  380. //change to task// if err != nil {
  381. //change to task// fmt.Println(err)
  382. //change to task// }
  383. //change to task// req.Header.Add("Version", "4")
  384. //change to task// req.Header.Add("Accept", "application/json")
  385. //change to task// req.Header.Add("Authorization", BA)
  386. //change to task// req.Header.Add("Content-Type", "application/json")
  387. //change to task// res, err := client.Do(req)
  388. //change to task// body, err := ioutil.ReadAll(res.Body)
  389. //change to task// //fmt.Println("len: ", len(_json))
  390. //change to task// //fmt.Println("res:", res)
  391. //change to task// if err != nil || res.StatusCode != 202 {
  392. //change to task// resp := _response{
  393. //change to task// Origin: "ovirt-addvm",
  394. //change to task// Message: res.Status,
  395. //change to task// Code: 1001,
  396. //change to task// }
  397. //change to task// b, _ := json.MarshalIndent(resp, "", " ")
  398. //change to task// return c.String(http.StatusBadRequest, string(b))
  399. //change to task// }
  400. //change to task// defer res.Body.Close()
  401. //addvmresponse := AddVMResponse{}O
  402. newvm := AddVMRequest{
  403. URL: url,
  404. JSON: struct {
  405. Name string `json:"name"`
  406. Description string `json:"description"`
  407. Comment string `json:"comment"`
  408. Cluster struct {
  409. Name string `json:"name"`
  410. } `json:"cluster"`
  411. Template struct {
  412. Name string `json:"name"`
  413. } `json:"template"`
  414. CPU struct {
  415. Topology struct {
  416. Sockets string `json:"sockets"`
  417. Cores string `json:"cores"`
  418. Threads string `json:"threads"`
  419. } `json:"topology"`
  420. } `json:"cpu"`
  421. Memory string `json:"memory"`
  422. MemoryPolicy struct {
  423. Ballooning string `json:"ballooning"`
  424. Guaranteed string `json:"guaranteed"`
  425. OverCommit struct {
  426. Percent string `json:"percent"`
  427. } `json:"over_commit"`
  428. } `json:"memory_policy"`
  429. }{
  430. Name: vmname,
  431. Description: vmdescr,
  432. Comment: vmcomment,
  433. Cluster: struct {
  434. Name string `json:"name"`
  435. }{Name: "Default"},
  436. Template: struct {
  437. Name string `json:"name"`
  438. }{Name: templatename},
  439. CPU: struct {
  440. Topology struct {
  441. Sockets string `json:"sockets"`
  442. Cores string `json:"cores"`
  443. Threads string `json:"threads"`
  444. } `json:"topology"`
  445. }{
  446. struct {
  447. Sockets string `json:"sockets"`
  448. Cores string `json:"cores"`
  449. Threads string `json:"threads"`
  450. }{
  451. Sockets: cpuSock,
  452. Cores: cpuCore,
  453. Threads: cpuThread,
  454. },
  455. },
  456. Memory: mem,
  457. MemoryPolicy: struct {
  458. Ballooning string `json:"ballooning"`
  459. Guaranteed string `json:"guaranteed"`
  460. OverCommit struct {
  461. Percent string `json:"percent"`
  462. } `json:"over_commit"`
  463. }{
  464. Ballooning: "true",
  465. Guaranteed: mem,
  466. OverCommit: struct {
  467. Percent string `json:"percent"`
  468. }{Percent: "10"},
  469. },
  470. },
  471. Method: method,
  472. Headers: nil,
  473. }
  474. newvm.Headers = append(newvm.Headers, struct {
  475. Name string `json:"Name"`
  476. Value string `json:"Value"`
  477. }{
  478. Name: "Accept",
  479. Value: "application/json",
  480. })
  481. newvm.Headers = append(newvm.Headers, struct {
  482. Name string `json:"Name"`
  483. Value string `json:"Value"`
  484. }{
  485. Name: "Authorization",
  486. Value: BA,
  487. })
  488. newvm.Headers = append(newvm.Headers, struct {
  489. Name string `json:"Name"`
  490. Value string `json:"Value"`
  491. }{
  492. Name: "Content-Type",
  493. Value: "application/json",
  494. })
  495. uuid, _ := uuidgen("APIGW-Ovirt-addVMTask")
  496. invoiceUUID, _ := uuidgen("APIGW-FakeInvoice")
  497. responseInvoiece:=AddVMPayment{
  498. Data: struct {
  499. Price struct {
  500. CPU string `json:"cpu"`
  501. Mem string `json:"mem"`
  502. Disk string `json:"disk"`
  503. Nic string `json:"nic"`
  504. Period string `json:"period"`
  505. } `json:"price"`
  506. InvoiceUUID string `json:"invoiceUUID"`
  507. }{
  508. Price: struct {
  509. CPU string `json:"cpu"`
  510. Mem string `json:"mem"`
  511. Disk string `json:"disk"`
  512. Nic string `json:"nic"`
  513. Period string `json:"period"`
  514. }{
  515. CPU: cpuThread,
  516. Mem: mem,
  517. Disk: Disk,
  518. Nic: nic,
  519. Period: period,
  520. },
  521. InvoiceUUID: invoiceUUID,
  522. },
  523. Message: "Done",
  524. Origin: "AddVM",
  525. Code: 1000,
  526. }
  527. __createVM, _ := json.MarshalIndent(newvm, "", " ")
  528. // Add VM Task
  529. addTask(uuid, string(__createVM), "", "APIGW", "VM Creation for "+claims["name"].(string), invoiceUUID, "0", "0")
  530. {
  531. db, err := sql.Open("mysql", MySQLUSER+":"+MySQLPASS+"@tcp(127.0.0.1:3306)/zicloud")
  532. if err != nil {
  533. resp := _response{
  534. Origin: "ovirt-addvm",
  535. Message: "Error on connecting db for save add vm result",
  536. Code: 1001,
  537. }
  538. b, _ := json.MarshalIndent(resp, "", " ")
  539. return c.String(http.StatusBadRequest, string(b))
  540. }
  541. defer db.Close()
  542. insert, err := db.Query("INSERT INTO service_profile VALUES ( '" + invoiceUUID + "'," +
  543. "'" + claims["IPAUid"].(string) + "'," +
  544. "'" + "VM" + "'," +
  545. "'" + "" + "'," +
  546. "'" + login(BA).AuthenticatedUser.ID + "'," +
  547. "NOW()" + "," +
  548. "NOW() ," +
  549. "false" + "," +
  550. "'" + vmname + "'," +
  551. "'" + invoiceUUID + "' )")
  552. defer insert.Close()
  553. if err != nil {
  554. fmt.Println("Error in addVM: ", err.Error())
  555. }
  556. }
  557. // Start Task
  558. {
  559. url := OvirtURL + "/ovirt-engine/api/vms/" + invoiceUUID + "/start"
  560. method := "POST"
  561. nicAddress := "172.20.15.251"
  562. nicMask := "255.255.255.0"
  563. nicGW := "172.20.15.1"
  564. __json := fmt.Sprintf(`
  565. {
  566. "async":"true",
  567. "use_cloud_init": "true",
  568. "vm": {
  569. "initialization": {
  570. "authorized_ssh_keys": "%s",
  571. "host_name": "Sassan.local",
  572. "user_name": "root",
  573. "root_password": "%s",
  574. "nic_configurations": {
  575. "nic_configuration": [
  576. {
  577. "name": "eth0",
  578. "on_boot": "true",
  579. "boot_protocol": "static",
  580. "ip": {
  581. "address": "%s",
  582. "netmask": "%s",
  583. "gateway": "%s"
  584. }
  585. }
  586. ]
  587. },
  588. "dns_servers": "172.20.11.11"
  589. }
  590. }
  591. }
  592. `, sshKey, rootpass, nicAddress, nicMask, nicGW)
  593. sha256 := sha256.Sum256([]byte(invoiceUUID))
  594. var hashChannel = make(chan []byte, 1)
  595. hashChannel <- sha256[:]
  596. ___json := encrypt(<-hashChannel, __json)
  597. startVM := addVMTask{
  598. URL: url,
  599. JSON: ___json,
  600. Method: method,
  601. Headers: nil,
  602. }
  603. startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Version", Value: "4"})
  604. startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Accept", Value: "application/json"})
  605. startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Content-Type", Value: "application/json"})
  606. startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Authorization", Value: BA})
  607. uuid, _ := uuidgen("APIGW-Ovirt-CloudInit")
  608. __startVM, _ := json.MarshalIndent(startVM, "", " ")
  609. //fmt.Println("StartVMHeaders: ", string(__startVMHeaders))
  610. addTask(uuid, string(__startVM), "", "APIGW", "VM Initialization", invoiceUUID, "1", "0")
  611. }
  612. //resp := _response{
  613. // Origin: "ovirt-addvm",
  614. // Message: resposeInvoice
  615. // Code: 1000,
  616. //}
  617. return c.JSON(http.StatusOK, responseInvoiece)
  618. }
  619. func (o ovirt) listVM(c echo.Context) error {
  620. user := c.Get("user").(*jwt.Token)
  621. claims := user.Claims.(jwt.MapClaims)
  622. _sha256 := sha256.Sum256([]byte(string(claims["name"].(string))))
  623. var hashChannel_ = make(chan []byte, 1)
  624. hashChannel_ <- _sha256[:]
  625. token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
  626. _BA := strings.Split(token, ";")
  627. BA := _BA[len(_BA)-2]
  628. url := OvirtURL + "/ovirt-engine/api/vms"
  629. client := &http.Client{}
  630. req, err := http.NewRequest("GET", url, nil)
  631. if err != nil {
  632. fmt.Println(err)
  633. }
  634. req.Header.Add("Version", "4")
  635. req.Header.Add("Accept", "application/json")
  636. req.Header.Add("Authorization", BA)
  637. res, err := client.Do(req)
  638. defer res.Body.Close()
  639. body, err := ioutil.ReadAll(res.Body)
  640. //fmt.Printf("%s",body)
  641. //b, _ := json.MarshalIndent(body, "", " ")
  642. resp := _response{
  643. Origin: "ovirt-listvms",
  644. Message: string(body),
  645. Code: 1000,
  646. }
  647. //b, _ := json.MarshalIndent(resp, "", " ")
  648. return c.JSON(http.StatusOK, resp)
  649. //return c.String(http.StatusOK, string(b))
  650. }
  651. func (o ovirt) StartVM(c echo.Context) error {
  652. vmuuid := c.FormValue("VmUUID")
  653. user := c.Get("user").(*jwt.Token)
  654. claims := user.Claims.(jwt.MapClaims)
  655. _sha256 := sha256.Sum256([]byte(string(claims["name"].(string))))
  656. var hashChannel_ = make(chan []byte, 1)
  657. hashChannel_ <- _sha256[:]
  658. token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
  659. _BA := strings.Split(token, ";")
  660. BA := _BA[len(_BA)-2]
  661. url := OvirtURL + "/ovirt-engine/api/vms/" + vmuuid + "/start"
  662. method := "POST"
  663. __json := "{\"async\":\"true\"}"
  664. sha256 := sha256.Sum256([]byte(vmuuid))
  665. var hashChannel = make(chan []byte, 1)
  666. hashChannel <- sha256[:]
  667. ___json := encrypt(<-hashChannel, __json)
  668. startVM := addVMTask{
  669. URL: url,
  670. JSON: ___json,
  671. Method: method,
  672. Headers: nil,
  673. }
  674. startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Version", Value: "4"})
  675. startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Accept", Value: "application/json"})
  676. startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Content-Type", Value: "application/json"})
  677. startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Authorization", Value: BA})
  678. //req.Header.Add("Version", "4")
  679. //req.Header.Add("Accept", "application/json")
  680. //req.Header.Add("Authorization", BA)
  681. //req.Header.Add("Content-Type", "application/json")
  682. //
  683. //res, err := client.Do(req)
  684. //defer res.Body.Close()
  685. uuid, _ := uuidgen("APIGW-Ovirt")
  686. __startVM, _ := json.MarshalIndent(startVM, "", " ")
  687. //fmt.Println("StartVMHeaders: ", string(__startVMHeaders))
  688. addTask(uuid, string(__startVM), "", "APIGW", "VM Start", vmuuid, "1", "1")
  689. resp := _response{
  690. Origin: "ovirt-StartVM",
  691. Message: "Done",
  692. Code: 1000,
  693. }
  694. //b, _ := json.MarshalIndent(resp, "", " ")
  695. return c.JSON(http.StatusOK, resp)
  696. //return c.String(http.StatusOK, string(b))
  697. }
  698. func (o ovirt) StopVM(c echo.Context) error {
  699. vmuuid := c.FormValue("VmUUID")
  700. user := c.Get("user").(*jwt.Token)
  701. claims := user.Claims.(jwt.MapClaims)
  702. _sha256 := sha256.Sum256([]byte(string(claims["name"].(string))))
  703. var hashChannel_ = make(chan []byte, 1)
  704. hashChannel_ <- _sha256[:]
  705. token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
  706. _BA := strings.Split(token, ";")
  707. BA := _BA[len(_BA)-2]
  708. url := OvirtURL + "/ovirt-engine/api/vms/" + vmuuid + "/shutdown"
  709. method := "POST"
  710. __json := "{\"async\":\"true\"}"
  711. sha256 := sha256.Sum256([]byte(vmuuid))
  712. var hashChannel = make(chan []byte, 1)
  713. hashChannel <- sha256[:]
  714. ___json := encrypt(<-hashChannel, __json)
  715. startVM := addVMTask{
  716. URL: url,
  717. JSON: ___json,
  718. Method: method,
  719. Headers: nil,
  720. }
  721. startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Version", Value: "4"})
  722. startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Accept", Value: "application/json"})
  723. startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Content-Type", Value: "application/json"})
  724. startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Authorization", Value: BA})
  725. //req.Header.Add("Version", "4")
  726. //req.Header.Add("Accept", "application/json")
  727. //req.Header.Add("Authorization", BA)
  728. //req.Header.Add("Content-Type", "application/json")
  729. //
  730. //res, err := client.Do(req)
  731. //defer res.Body.Close()
  732. uuid, _ := uuidgen("APIGW-Ovirt")
  733. __startVM, _ := json.MarshalIndent(startVM, "", " ")
  734. //fmt.Println("StartVMHeaders: ", string(__startVMHeaders))
  735. addTask(uuid, string(__startVM), "", "APIGW", "VM Start", vmuuid, "1", "1")
  736. resp := _response{
  737. Origin: "ovirt-StopVM",
  738. Message: "Done",
  739. Code: 1000,
  740. }
  741. //b, _ := json.MarshalIndent(resp, "", " ")
  742. return c.JSON(http.StatusOK, resp)
  743. //return c.String(http.StatusOK, string(b))
  744. }
  745. func (o ovirt) RebootVM(c echo.Context) error {
  746. vmuuid := c.FormValue("VmUUID")
  747. user := c.Get("user").(*jwt.Token)
  748. claims := user.Claims.(jwt.MapClaims)
  749. _sha256 := sha256.Sum256([]byte(string(claims["name"].(string))))
  750. var hashChannel_ = make(chan []byte, 1)
  751. hashChannel_ <- _sha256[:]
  752. token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
  753. _BA := strings.Split(token, ";")
  754. BA := _BA[len(_BA)-2]
  755. url := OvirtURL + "/ovirt-engine/api/vms/" + vmuuid + "/reboot"
  756. method := "POST"
  757. __json := "{\"async\":\"true\"}"
  758. sha256 := sha256.Sum256([]byte(vmuuid))
  759. var hashChannel = make(chan []byte, 1)
  760. hashChannel <- sha256[:]
  761. ___json := encrypt(<-hashChannel, __json)
  762. startVM := addVMTask{
  763. URL: url,
  764. JSON: ___json,
  765. Method: method,
  766. Headers: nil,
  767. }
  768. startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Version", Value: "4"})
  769. startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Accept", Value: "application/json"})
  770. startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Content-Type", Value: "application/json"})
  771. startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Authorization", Value: BA})
  772. //req.Header.Add("Version", "4")
  773. //req.Header.Add("Accept", "application/json")
  774. //req.Header.Add("Authorization", BA)
  775. //req.Header.Add("Content-Type", "application/json")
  776. //
  777. //res, err := client.Do(req)
  778. //defer res.Body.Close()
  779. uuid, _ := uuidgen("APIGW-Ovirt")
  780. __startVM, _ := json.MarshalIndent(startVM, "", " ")
  781. //fmt.Println("StartVMHeaders: ", string(__startVMHeaders))
  782. addTask(uuid, string(__startVM), "", "APIGW", "VM Start", vmuuid, "1", "1")
  783. resp := _response{
  784. Origin: "ovirt-RebootVM",
  785. Message: "Done",
  786. Code: 1000,
  787. }
  788. //b, _ := json.MarshalIndent(resp, "", " ")
  789. //return c.String(http.StatusOK, string(b))
  790. return c.JSON(http.StatusOK, resp)
  791. }
  792. func (o ovirt) PowerOffVM(c echo.Context) error {
  793. vmuuid := c.FormValue("VmUUID")
  794. user := c.Get("user").(*jwt.Token)
  795. claims := user.Claims.(jwt.MapClaims)
  796. _sha256 := sha256.Sum256([]byte(string(claims["name"].(string))))
  797. var hashChannel_ = make(chan []byte, 1)
  798. hashChannel_ <- _sha256[:]
  799. token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
  800. _BA := strings.Split(token, ";")
  801. BA := _BA[len(_BA)-2]
  802. url := OvirtURL + "/ovirt-engine/api/vms/" + vmuuid + "/stop"
  803. method := "POST"
  804. __json := "{\"async\":\"true\"}"
  805. sha256 := sha256.Sum256([]byte(vmuuid))
  806. var hashChannel = make(chan []byte, 1)
  807. hashChannel <- sha256[:]
  808. ___json := encrypt(<-hashChannel, __json)
  809. startVM := addVMTask{
  810. URL: url,
  811. JSON: ___json,
  812. Method: method,
  813. Headers: nil,
  814. }
  815. startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Version", Value: "4"})
  816. startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Accept", Value: "application/json"})
  817. startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Content-Type", Value: "application/json"})
  818. startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Authorization", Value: BA})
  819. //req.Header.Add("Version", "4")
  820. //req.Header.Add("Accept", "application/json")
  821. //req.Header.Add("Authorization", BA)
  822. //req.Header.Add("Content-Type", "application/json")
  823. //
  824. //res, err := client.Do(req)
  825. //defer res.Body.Close()
  826. uuid, _ := uuidgen("APIGW-Ovirt")
  827. __startVM, _ := json.MarshalIndent(startVM, "", " ")
  828. //fmt.Println("StartVMHeaders: ", string(__startVMHeaders))
  829. addTask(uuid, string(__startVM), "", "APIGW", "VM Start", vmuuid, "1", "1")
  830. resp := _response{
  831. Origin: "ovirt-PowerOffVM",
  832. Message: "Done",
  833. Code: 1000,
  834. }
  835. //b, _ := json.MarshalIndent(resp, "", " ")
  836. //return c.String(http.StatusOK, string(b))
  837. return c.JSON(http.StatusOK, resp)
  838. }
  839. func (o ovirt) ResetVM(c echo.Context) error {
  840. resp := _response{
  841. Origin: "ovirt-ResetVM",
  842. Message: "not implemented",
  843. Code: 1003,
  844. }
  845. //b, _ := json.MarshalIndent(resp, "", " ")
  846. return c.JSON(http.StatusOK, resp)
  847. //return c.String(http.StatusOK, string(b))
  848. }
  849. func (o ovirt) AddNIC(c echo.Context) error {
  850. resp := _response{
  851. Origin: "ovirt-AddNIC",
  852. Message: "Done",
  853. Code: 1000,
  854. }
  855. //b, _ := json.MarshalIndent(resp, "", " ")
  856. //return c.String(http.StatusOK, string(b))
  857. return c.JSON(http.StatusOK, resp)
  858. }
  859. func (o ovirt) AddDisk(c echo.Context) error {
  860. resp := _response{
  861. Origin: "ovirt-AddDisk",
  862. Message: "Done",
  863. Code: 1000,
  864. }
  865. //b, _ := json.MarshalIndent(resp, "", " ")
  866. //return c.String(http.StatusOK, string(b))
  867. return c.JSON(http.StatusOK, resp)
  868. }
  869. func (o ovirt) EditVM(c echo.Context) error {
  870. resp := _response{
  871. Origin: "ovirt-EditVM",
  872. Message: "Done",
  873. Code: 1000,
  874. }
  875. //b, _ := json.MarshalIndent(resp, "", " ")
  876. //return c.String(http.StatusOK, string(b))
  877. return c.JSON(http.StatusOK, resp)
  878. }
  879. func (o ovirt) ResetPassword(c echo.Context) error {
  880. resp := _response{
  881. Origin: "ovirt-ResetPassword",
  882. Message: "not implemented",
  883. Code: 1003,
  884. }
  885. //b, _ := json.MarshalIndent(resp, "", " ")
  886. //return c.String(http.StatusOK, string(b))
  887. return c.JSON(http.StatusOK, resp)
  888. }
  889. func createVM(invoice_uuid string, apiJson string, uuid string) {
  890. type AddVMResponse struct {
  891. NextRunConfigurationExists string `json:"next_run_configuration_exists"`
  892. NumaTuneMode string `json:"numa_tune_mode"`
  893. Status string `json:"status"`
  894. StopTime int64 `json:"stop_time"`
  895. OriginalTemplate struct {
  896. Href string `json:"href"`
  897. ID string `json:"id"`
  898. } `json:"original_template"`
  899. Template struct {
  900. Href string `json:"href"`
  901. ID string `json:"id"`
  902. } `json:"template"`
  903. Actions struct {
  904. Link []struct {
  905. Href string `json:"href"`
  906. Rel string `json:"rel"`
  907. } `json:"link"`
  908. } `json:"actions"`
  909. Name string `json:"name"`
  910. Description string `json:"description"`
  911. Comment string `json:"comment"`
  912. Href string `json:"href"`
  913. ID string `json:"id"`
  914. Bios struct {
  915. BootMenu struct {
  916. Enabled string `json:"enabled"`
  917. } `json:"boot_menu"`
  918. Type string `json:"type"`
  919. } `json:"bios"`
  920. Console struct {
  921. Enabled string `json:"enabled"`
  922. } `json:"console"`
  923. CPU struct {
  924. Architecture string `json:"architecture"`
  925. Topology struct {
  926. Cores string `json:"cores"`
  927. Sockets string `json:"sockets"`
  928. Threads string `json:"threads"`
  929. } `json:"topology"`
  930. } `json:"cpu"`
  931. Display struct {
  932. AllowOverride string `json:"allow_override"`
  933. CopyPasteEnabled string `json:"copy_paste_enabled"`
  934. DisconnectAction string `json:"disconnect_action"`
  935. FileTransferEnabled string `json:"file_transfer_enabled"`
  936. Monitors string `json:"monitors"`
  937. SingleQxlPci string `json:"single_qxl_pci"`
  938. SmartcardEnabled string `json:"smartcard_enabled"`
  939. Type string `json:"type"`
  940. } `json:"display"`
  941. Initialization struct {
  942. AuthorizedSSHKeys string `json:"authorized_ssh_keys"`
  943. CloudInitNetworkProtocol string `json:"cloud_init_network_protocol"`
  944. CustomScript string `json:"custom_script"`
  945. HostName string `json:"host_name"`
  946. NicConfigurations struct {
  947. } `json:"nic_configurations"`
  948. RegenerateSSHKeys string `json:"regenerate_ssh_keys"`
  949. UserName string `json:"user_name"`
  950. } `json:"initialization"`
  951. Io struct {
  952. Threads string `json:"threads"`
  953. } `json:"io"`
  954. Memory string `json:"memory"`
  955. Migration struct {
  956. AutoConverge string `json:"auto_converge"`
  957. Compressed string `json:"compressed"`
  958. Encrypted string `json:"encrypted"`
  959. } `json:"migration"`
  960. Origin string `json:"origin"`
  961. Os struct {
  962. Boot struct {
  963. Devices struct {
  964. Device []string `json:"device"`
  965. } `json:"devices"`
  966. } `json:"boot"`
  967. Type string `json:"type"`
  968. } `json:"os"`
  969. Sso struct {
  970. Methods struct {
  971. Method []struct {
  972. ID string `json:"id"`
  973. } `json:"method"`
  974. } `json:"methods"`
  975. } `json:"sso"`
  976. Stateless string `json:"stateless"`
  977. Type string `json:"type"`
  978. Usb struct {
  979. Enabled string `json:"enabled"`
  980. } `json:"usb"`
  981. Cluster struct {
  982. Href string `json:"href"`
  983. ID string `json:"id"`
  984. } `json:"cluster"`
  985. Quota struct {
  986. ID string `json:"id"`
  987. } `json:"quota"`
  988. CreationStatus string `json:"creation_status"`
  989. Link []struct {
  990. Href string `json:"href"`
  991. Rel string `json:"rel"`
  992. } `json:"link"`
  993. CPUShares string `json:"cpu_shares"`
  994. CreationTime int64 `json:"creation_time"`
  995. DeleteProtected string `json:"delete_protected"`
  996. HighAvailability struct {
  997. Enabled string `json:"enabled"`
  998. Priority string `json:"priority"`
  999. } `json:"high_availability"`
  1000. LargeIcon struct {
  1001. Href string `json:"href"`
  1002. ID string `json:"id"`
  1003. } `json:"large_icon"`
  1004. MemoryPolicy struct {
  1005. Ballooning string `json:"ballooning"`
  1006. Guaranteed string `json:"guaranteed"`
  1007. Max string `json:"max"`
  1008. } `json:"memory_policy"`
  1009. MigrationDowntime string `json:"migration_downtime"`
  1010. MultiQueuesEnabled string `json:"multi_queues_enabled"`
  1011. RngDevice struct {
  1012. Source string `json:"source"`
  1013. } `json:"rng_device"`
  1014. SmallIcon struct {
  1015. Href string `json:"href"`
  1016. ID string `json:"id"`
  1017. } `json:"small_icon"`
  1018. SoundcardEnabled string `json:"soundcard_enabled"`
  1019. StartPaused string `json:"start_paused"`
  1020. StorageErrorResumeBehaviour string `json:"storage_error_resume_behaviour"`
  1021. TimeZone struct {
  1022. Name string `json:"name"`
  1023. } `json:"time_zone"`
  1024. VirtioScsi struct {
  1025. Enabled string `json:"enabled"`
  1026. } `json:"virtio_scsi"`
  1027. CPUProfile struct {
  1028. Href string `json:"href"`
  1029. ID string `json:"id"`
  1030. } `json:"cpu_profile"`
  1031. }
  1032. _createVM := AddVMRequest{}
  1033. //fmt.Println(apiJson)
  1034. _err := json.Unmarshal([]byte(apiJson), &_createVM)
  1035. if _err != nil {
  1036. fmt.Println("Error in VMCreation step 1: ", _err.Error())
  1037. }
  1038. addvmresponse := AddVMResponse{}
  1039. var body []byte
  1040. {
  1041. url := _createVM.URL
  1042. method := _createVM.Method
  1043. __json := _createVM.JSON
  1044. client := &http.Client{}
  1045. _json, _ := json.Marshal(__json)
  1046. payload := strings.NewReader(string(_json))
  1047. //payload := __json
  1048. req, err := http.NewRequest(method, url, payload)
  1049. if err != nil {
  1050. fmt.Println("Error in VMCreation step 2: ", err.Error())
  1051. }
  1052. _headers := _createVM.Headers
  1053. for _, v := range _headers {
  1054. req.Header.Add(v.Name, v.Value)
  1055. }
  1056. if err != nil {
  1057. fmt.Println("Error in VMCreation step 3: ", err.Error())
  1058. }
  1059. res, err := client.Do(req)
  1060. defer res.Body.Close()
  1061. body, _ = ioutil.ReadAll(res.Body)
  1062. }
  1063. //body := runAPICall(_createVM)
  1064. err := json.Unmarshal(body, &addvmresponse)
  1065. if err != nil {
  1066. fmt.Println("Error in VMCreation step 4: ", err.Error())
  1067. }
  1068. toggleTask(uuid, 0)
  1069. // find related VMInitialization Task
  1070. //ruuid := ""
  1071. {
  1072. db, err := sql.Open("mysql", MySQLUSER+":"+MySQLPASS+"@tcp(127.0.0.1:3306)/zicloud")
  1073. if err != nil {
  1074. fmt.Println("Error in VMCreation step 3: ", _err.Error())
  1075. }
  1076. //defer db.Close()
  1077. //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")
  1078. //type Task struct {
  1079. // UUID string `json:"uuid"`
  1080. // TaskAPICall string `json:"taskapicall"`
  1081. // Ruuid string `json:"ruuid"`
  1082. // CronExpression string `json:"cronexpression"`
  1083. // Type string `json:"type"`
  1084. //}
  1085. //for results.Next() {
  1086. // var res Task
  1087. // err = results.Scan(&res.UUID, &res.TaskAPICall, &res.CronExpression, &res.Ruuid, &res.Type)
  1088. // ruuid = res.UUID
  1089. // break
  1090. //}
  1091. //update UUID and status
  1092. update2, err := db.Query("update service_profile set uuid='" + addvmresponse.ID + "' , active=1 where related_invoice='" + invoice_uuid + "'")
  1093. update, err := db.Query("update scheduler set related_uuid='" + addvmresponse.ID + "' , active=1 where related_uuid='" + invoice_uuid + "' and type=1")
  1094. defer update.Close()
  1095. defer update2.Close()
  1096. //toggleTask(ruuid, 1)
  1097. }
  1098. }
  1099. func VMInitialization(relatedUuid string, apiCall string, uuid string) {
  1100. iaas := &ovirt{}
  1101. status := iaas.vmStatus(relatedUuid)
  1102. //fmt.Println("VM :", relatedUuid, " is now: ", status)
  1103. if status == "down" {
  1104. //fmt.Println("APICall: ", apiCall)
  1105. startVM := addVMTask{}
  1106. //b, _ := json.Marshal(apiCall)
  1107. _err := json.Unmarshal([]byte(apiCall), &startVM)
  1108. if _err != nil {
  1109. fmt.Println("Error in VMInitialization: ", _err.Error())
  1110. }
  1111. //fmt.Println("calling initialization for VM :", relatedUuid)
  1112. words := strings.Split(startVM.URL, "/")
  1113. //fmt.Println("Invoice : ", words[6])
  1114. _sha256 := sha256.Sum256([]byte(words[6]))
  1115. var hashChannel_ = make(chan []byte, 1)
  1116. hashChannel_ <- _sha256[:]
  1117. //fmt.Println(" startVM.JSON: ", startVM.JSON)
  1118. startVM.JSON = decrypt(<-hashChannel_, startVM.JSON)
  1119. //fmt.Println("decrypted json: ",startVM.JSON)
  1120. startVM.URL = OvirtURL + "/ovirt-engine/api/vms/" + relatedUuid + "/start"
  1121. //fmt.Println("Start URL: ", startVM.URL)
  1122. //fmt.Println("Initialize JSON: ", decrypt(<-hashChannel_, startVM.JSON))
  1123. runAPICall(startVM)
  1124. toggleTask(uuid, 0)
  1125. }
  1126. }
  1127. func vmStatistics(BA string, VMUUID string) (string, float64, float64) {
  1128. //ram,cpu,storage
  1129. var _disk []string
  1130. {
  1131. type DiskAttachments struct {
  1132. DiskAttachment []struct {
  1133. Active string `json:"active"`
  1134. Bootable string `json:"bootable"`
  1135. Interface string `json:"interface"`
  1136. LogicalName string `json:"logical_name"`
  1137. PassDiscard string `json:"pass_discard"`
  1138. ReadOnly string `json:"read_only"`
  1139. UsesScsiReservation string `json:"uses_scsi_reservation"`
  1140. Disk struct {
  1141. Href string `json:"href"`
  1142. ID string `json:"id"`
  1143. } `json:"disk"`
  1144. VM struct {
  1145. Href string `json:"href"`
  1146. ID string `json:"id"`
  1147. } `json:"vm"`
  1148. Href string `json:"href"`
  1149. ID string `json:"id"`
  1150. } `json:"disk_attachment"`
  1151. }
  1152. url := OvirtURL + "/ovirt-engine/api/vms/" + VMUUID + "/diskattachments"
  1153. //fmt.Println("Url:" ,url)
  1154. method := "GET"
  1155. client := &http.Client{}
  1156. req, err := http.NewRequest(method, url, nil)
  1157. if err != nil {
  1158. return "", -1, -1
  1159. }
  1160. req.Header.Add("Version", "4")
  1161. req.Header.Add("Accept", "application/json")
  1162. req.Header.Add("Authorization", BA)
  1163. res, err := client.Do(req)
  1164. defer res.Body.Close()
  1165. body, err := ioutil.ReadAll(res.Body)
  1166. diskattachments := DiskAttachments{}
  1167. _err := json.Unmarshal(body, &diskattachments)
  1168. if _err != nil {
  1169. fmt.Println("Error in vmStatistics 1: ", _err)
  1170. }
  1171. for _, v := range diskattachments.DiskAttachment {
  1172. url := OvirtURL + "/ovirt-engine/api/disks/" + v.Disk.ID
  1173. type DiskAttachment struct {
  1174. ActualSize string `json:"actual_size"`
  1175. Alias string `json:"alias"`
  1176. Backup string `json:"backup"`
  1177. ContentType string `json:"content_type"`
  1178. Format string `json:"format"`
  1179. ImageID string `json:"image_id"`
  1180. PropagateErrors string `json:"propagate_errors"`
  1181. ProvisionedSize string `json:"provisioned_size"`
  1182. QcowVersion string `json:"qcow_version"`
  1183. Shareable string `json:"shareable"`
  1184. Sparse string `json:"sparse"`
  1185. Status string `json:"status"`
  1186. StorageType string `json:"storage_type"`
  1187. TotalSize string `json:"total_size"`
  1188. WipeAfterDelete string `json:"wipe_after_delete"`
  1189. DiskProfile struct {
  1190. Href string `json:"href"`
  1191. ID string `json:"id"`
  1192. } `json:"disk_profile"`
  1193. Quota struct {
  1194. Href string `json:"href"`
  1195. ID string `json:"id"`
  1196. } `json:"quota"`
  1197. StorageDomains struct {
  1198. StorageDomain []struct {
  1199. Href string `json:"href"`
  1200. ID string `json:"id"`
  1201. } `json:"storage_domain"`
  1202. } `json:"storage_domains"`
  1203. Actions struct {
  1204. Link []struct {
  1205. Href string `json:"href"`
  1206. Rel string `json:"rel"`
  1207. } `json:"link"`
  1208. } `json:"actions"`
  1209. Name string `json:"name"`
  1210. Description string `json:"description"`
  1211. Href string `json:"href"`
  1212. ID string `json:"id"`
  1213. Link []struct {
  1214. Href string `json:"href"`
  1215. Rel string `json:"rel"`
  1216. } `json:"link"`
  1217. }
  1218. //fmt.Println("Url:" ,url)
  1219. method := "GET"
  1220. client := &http.Client{}
  1221. req, _ := http.NewRequest(method, url, nil)
  1222. //if err != nil {
  1223. // return "Null"
  1224. //}
  1225. req.Header.Add("Version", "4")
  1226. req.Header.Add("Accept", "application/json")
  1227. req.Header.Add("Authorization", BA)
  1228. res, _ := client.Do(req)
  1229. defer res.Body.Close()
  1230. body, _ := ioutil.ReadAll(res.Body)
  1231. //fmt.Println("full response: ",string(body))
  1232. disk := DiskAttachment{}
  1233. _err := json.Unmarshal(body, &disk)
  1234. if _err != nil {
  1235. fmt.Println("Error in vmStatistics 2 : ", _err)
  1236. }
  1237. _disk = append(_disk, disk.ProvisionedSize)
  1238. //_disk = D_disk + "" + disk.ProvisionedSize+" "
  1239. }
  1240. }
  1241. url := OvirtURL + "/ovirt-engine/api/vms/" + VMUUID + "/statistics"
  1242. //fmt.Println("Url:" ,url)
  1243. method := "GET"
  1244. client := &http.Client{}
  1245. req, err := http.NewRequest(method, url, nil)
  1246. if err != nil {
  1247. return "", -1, -1
  1248. }
  1249. req.Header.Add("Version", "4")
  1250. req.Header.Add("Accept", "application/json")
  1251. req.Header.Add("Authorization", BA)
  1252. res, err := client.Do(req)
  1253. defer res.Body.Close()
  1254. body, err := ioutil.ReadAll(res.Body)
  1255. //fmt.Println("full response: ",string(body))
  1256. _vmstatistics := VMStatistics{}
  1257. _err := json.Unmarshal(body, &_vmstatistics)
  1258. if _err != nil {
  1259. fmt.Println("Error in vmStatistics 3: ", _err)
  1260. }
  1261. cpuUUID := _vmstatistics.Statistic[4].ID
  1262. memUsedUUID := _vmstatistics.Statistic[1].ID
  1263. memTotalUUID := _vmstatistics.Statistic[0].ID
  1264. //fmt.Println(memUsedUUID)
  1265. var cpu, memUsed, memTotal string
  1266. type ItemUsage struct {
  1267. Kind string `json:"kind"`
  1268. Type string `json:"type"`
  1269. Unit string `json:"unit"`
  1270. Values struct {
  1271. Value []struct {
  1272. Datum float64 `json:"datum"`
  1273. } `json:"value"`
  1274. } `json:"values"`
  1275. VM struct {
  1276. Href string `json:"href"`
  1277. ID string `json:"id"`
  1278. } `json:"vm"`
  1279. Name string `json:"name"`
  1280. Description string `json:"description"`
  1281. Href string `json:"href"`
  1282. ID string `json:"id"`
  1283. }
  1284. {
  1285. url := OvirtURL + "/ovirt-engine/api/vms/" + VMUUID + "/statistics/" + cpuUUID
  1286. //fmt.Println("Url:" ,url)
  1287. method := "GET"
  1288. client := &http.Client{}
  1289. req, err := http.NewRequest(method, url, nil)
  1290. if err != nil {
  1291. return "", -1, -1
  1292. }
  1293. req.Header.Add("Version", "4")
  1294. req.Header.Add("Accept", "application/json")
  1295. req.Header.Add("Authorization", BA)
  1296. res, err := client.Do(req)
  1297. defer res.Body.Close()
  1298. body, err := ioutil.ReadAll(res.Body)
  1299. cpuUsage := ItemUsage{}
  1300. _err := json.Unmarshal(body, &cpuUsage)
  1301. if _err != nil {
  1302. fmt.Println("Error in vmStatistics 4 ", _err)
  1303. }
  1304. cpu = fmt.Sprintf("%f", cpuUsage.Values.Value[0].Datum)
  1305. }
  1306. {
  1307. url := OvirtURL + "/ovirt-engine/api/vms/" + VMUUID + "/statistics/" + memUsedUUID
  1308. //fmt.Println("Url:" ,url)
  1309. method := "GET"
  1310. client := &http.Client{}
  1311. req, err := http.NewRequest(method, url, nil)
  1312. if err != nil {
  1313. return "", -1, -1
  1314. }
  1315. req.Header.Add("Version", "4")
  1316. req.Header.Add("Accept", "application/json")
  1317. req.Header.Add("Authorization", BA)
  1318. res, err := client.Do(req)
  1319. defer res.Body.Close()
  1320. body, err := ioutil.ReadAll(res.Body)
  1321. memUsage := ItemUsage{}
  1322. _err := json.Unmarshal(body, &memUsage)
  1323. if _err != nil {
  1324. fmt.Println("Error in vmStatistics 5: ", _err)
  1325. }
  1326. memUsed = fmt.Sprintf("%f", memUsage.Values.Value[0].Datum)
  1327. }
  1328. {
  1329. url := OvirtURL + "/ovirt-engine/api/vms/" + VMUUID + "/statistics/" + memTotalUUID
  1330. //fmt.Println("Url:" ,url)
  1331. method := "GET"
  1332. client := &http.Client{}
  1333. req, err := http.NewRequest(method, url, nil)
  1334. if err != nil {
  1335. return "", -1, -1
  1336. }
  1337. req.Header.Add("Version", "4")
  1338. req.Header.Add("Accept", "application/json")
  1339. req.Header.Add("Authorization", BA)
  1340. res, err := client.Do(req)
  1341. defer res.Body.Close()
  1342. body, err := ioutil.ReadAll(res.Body)
  1343. memUsage := ItemUsage{}
  1344. _err := json.Unmarshal(body, &memUsage)
  1345. if _err != nil {
  1346. fmt.Println("Error in vmStatistics 6: ", _err)
  1347. }
  1348. memTotal = fmt.Sprintf("%f", memUsage.Values.Value[0].Datum)
  1349. }
  1350. //fmt.Println("CPU:" ,cpu)
  1351. //fmt.Println("MEM:", memUsed)
  1352. //fmt.Println("MEM:", memTotal)
  1353. _memusage, _ := strconv.ParseFloat(memUsed, 32)
  1354. _memtotal, _ := strconv.ParseFloat(memTotal, 32)
  1355. mem := _memusage / _memtotal
  1356. _cpu, _ := strconv.ParseFloat(cpu, 64)
  1357. return strings.Join(_disk, ", "), _cpu, mem
  1358. }
  1359. func (o ovirt) vmDetails(c echo.Context) error {
  1360. //name,...,traffic,ip,status
  1361. user := c.Get("user").(*jwt.Token)
  1362. claims := user.Claims.(jwt.MapClaims)
  1363. _sha256 := sha256.Sum256([]byte(string(claims["name"].(string))))
  1364. var hashChannel_ = make(chan []byte, 1)
  1365. hashChannel_ <- _sha256[:]
  1366. token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
  1367. _BA := strings.Split(token, ";")
  1368. BA := _BA[len(_BA)-2]
  1369. uuid := c.FormValue("uuid")
  1370. if len(uuid) < 5 {
  1371. resp := _response{
  1372. Origin: "AddUser",
  1373. Message: "Missing UUID",
  1374. Code: 1001,
  1375. }
  1376. return c.JSON(http.StatusNotFound, resp)
  1377. }
  1378. type vmStatus struct {
  1379. NextRunConfigurationExists string `json:"next_run_configuration_exists"`
  1380. NumaTuneMode string `json:"numa_tune_mode"`
  1381. Status string `json:"status"`
  1382. StopTime int64 `json:"stop_time"`
  1383. OriginalTemplate struct {
  1384. Href string `json:"href"`
  1385. ID string `json:"id"`
  1386. } `json:"original_template"`
  1387. Template struct {
  1388. Href string `json:"href"`
  1389. ID string `json:"id"`
  1390. } `json:"template"`
  1391. Actions struct {
  1392. Link []struct {
  1393. Href string `json:"href"`
  1394. Rel string `json:"rel"`
  1395. } `json:"link"`
  1396. } `json:"actions"`
  1397. Name string `json:"name"`
  1398. Description string `json:"description"`
  1399. Comment string `json:"comment"`
  1400. Href string `json:"href"`
  1401. ID string `json:"id"`
  1402. Bios struct {
  1403. BootMenu struct {
  1404. Enabled string `json:"enabled"`
  1405. } `json:"boot_menu"`
  1406. Type string `json:"type"`
  1407. } `json:"bios"`
  1408. CPU struct {
  1409. Architecture string `json:"architecture"`
  1410. Topology struct {
  1411. Cores string `json:"cores"`
  1412. Sockets string `json:"sockets"`
  1413. Threads string `json:"threads"`
  1414. } `json:"topology"`
  1415. } `json:"cpu"`
  1416. Display struct {
  1417. AllowOverride string `json:"allow_override"`
  1418. CopyPasteEnabled string `json:"copy_paste_enabled"`
  1419. DisconnectAction string `json:"disconnect_action"`
  1420. FileTransferEnabled string `json:"file_transfer_enabled"`
  1421. Monitors string `json:"monitors"`
  1422. SingleQxlPci string `json:"single_qxl_pci"`
  1423. SmartcardEnabled string `json:"smartcard_enabled"`
  1424. Type string `json:"type"`
  1425. } `json:"display"`
  1426. Initialization struct {
  1427. AuthorizedSSHKeys string `json:"authorized_ssh_keys"`
  1428. CloudInitNetworkProtocol string `json:"cloud_init_network_protocol"`
  1429. CustomScript string `json:"custom_script"`
  1430. HostName string `json:"host_name"`
  1431. NicConfigurations struct {
  1432. } `json:"nic_configurations"`
  1433. RegenerateSSHKeys string `json:"regenerate_ssh_keys"`
  1434. UserName string `json:"user_name"`
  1435. } `json:"initialization"`
  1436. Io struct {
  1437. Threads string `json:"threads"`
  1438. } `json:"io"`
  1439. Memory string `json:"memory"`
  1440. Migration struct {
  1441. AutoConverge string `json:"auto_converge"`
  1442. Compressed string `json:"compressed"`
  1443. Encrypted string `json:"encrypted"`
  1444. } `json:"migration"`
  1445. Origin string `json:"origin"`
  1446. Os struct {
  1447. Boot struct {
  1448. Devices struct {
  1449. Device []string `json:"device"`
  1450. } `json:"devices"`
  1451. } `json:"boot"`
  1452. Type string `json:"type"`
  1453. } `json:"os"`
  1454. Sso struct {
  1455. Methods struct {
  1456. Method []struct {
  1457. ID string `json:"id"`
  1458. } `json:"method"`
  1459. } `json:"methods"`
  1460. } `json:"sso"`
  1461. Stateless string `json:"stateless"`
  1462. Type string `json:"type"`
  1463. Usb struct {
  1464. Enabled string `json:"enabled"`
  1465. } `json:"usb"`
  1466. Cluster struct {
  1467. Href string `json:"href"`
  1468. ID string `json:"id"`
  1469. } `json:"cluster"`
  1470. Quota struct {
  1471. ID string `json:"id"`
  1472. } `json:"quota"`
  1473. Link []struct {
  1474. Href string `json:"href"`
  1475. Rel string `json:"rel"`
  1476. } `json:"link"`
  1477. CPUShares string `json:"cpu_shares"`
  1478. CreationTime int64 `json:"creation_time"`
  1479. DeleteProtected string `json:"delete_protected"`
  1480. HighAvailability struct {
  1481. Enabled string `json:"enabled"`
  1482. Priority string `json:"priority"`
  1483. } `json:"high_availability"`
  1484. LargeIcon struct {
  1485. Href string `json:"href"`
  1486. ID string `json:"id"`
  1487. } `json:"large_icon"`
  1488. MemoryPolicy struct {
  1489. Ballooning string `json:"ballooning"`
  1490. Guaranteed string `json:"guaranteed"`
  1491. Max string `json:"max"`
  1492. } `json:"memory_policy"`
  1493. MigrationDowntime string `json:"migration_downtime"`
  1494. MultiQueuesEnabled string `json:"multi_queues_enabled"`
  1495. PlacementPolicy struct {
  1496. Affinity string `json:"affinity"`
  1497. Hosts struct {
  1498. Host []struct {
  1499. Href string `json:"href"`
  1500. ID string `json:"id"`
  1501. } `json:"host"`
  1502. } `json:"hosts"`
  1503. } `json:"placement_policy"`
  1504. SmallIcon struct {
  1505. Href string `json:"href"`
  1506. ID string `json:"id"`
  1507. } `json:"small_icon"`
  1508. StartPaused string `json:"start_paused"`
  1509. StorageErrorResumeBehaviour string `json:"storage_error_resume_behaviour"`
  1510. TimeZone struct {
  1511. Name string `json:"name"`
  1512. } `json:"time_zone"`
  1513. CPUProfile struct {
  1514. Href string `json:"href"`
  1515. ID string `json:"id"`
  1516. } `json:"cpu_profile"`
  1517. }
  1518. //url := "https://ovirt-cl.zi-tel.com/ovirt-engine/api/vms/c1a44128-6c6c-406b-99d8-4a68a99380c9"
  1519. url := OvirtURL + "/ovirt-engine/api/vms/" + uuid
  1520. //fmt.Println("Url:" ,url)
  1521. method := "GET"
  1522. client := &http.Client{}
  1523. req, _ := http.NewRequest(method, url, nil)
  1524. //if err != nil {
  1525. // return "Null"
  1526. //}
  1527. req.Header.Add("Version", "4")
  1528. req.Header.Add("Accept", "application/json")
  1529. req.Header.Add("Authorization", BA)
  1530. res, _ := client.Do(req)
  1531. defer res.Body.Close()
  1532. body, _ := ioutil.ReadAll(res.Body)
  1533. //fmt.Println("full response: ",string(body))
  1534. _vmstatus := vmStatus{}
  1535. _err := json.Unmarshal(body, &_vmstatus)
  1536. if _err != nil {
  1537. fmt.Println("Error in vmDetails : ", _err)
  1538. }
  1539. disk, cpu, ram := vmStatistics(BA, uuid)
  1540. type AutoGenerated struct {
  1541. Message struct {
  1542. Disk string `json:"Disk"`
  1543. Memory string `json:"Memory"`
  1544. CPU string `json:"CPU"`
  1545. NetAddress string `json:"NetAddress"`
  1546. Traffic string `json:"Traffic"`
  1547. Status string `json:"Status"`
  1548. Name string `json:"Name"`
  1549. } `json:"message"`
  1550. Origin string `json:"origin"`
  1551. Code int `json:"code"`
  1552. }
  1553. resp := AutoGenerated{
  1554. Message: struct {
  1555. Disk string `json:"Disk"`
  1556. Memory string `json:"Memory"`
  1557. CPU string `json:"CPU"`
  1558. NetAddress string `json:"NetAddress"`
  1559. Traffic string `json:"Traffic"`
  1560. Status string `json:"Status"`
  1561. Name string `json:"Name"`
  1562. }{
  1563. Disk: disk,
  1564. Memory: fmt.Sprintf("%f", ram),
  1565. CPU: fmt.Sprintf("%f", cpu),
  1566. NetAddress: "",
  1567. Traffic: "",
  1568. Status: _vmstatus.Status,
  1569. Name: _vmstatus.Name,
  1570. },
  1571. Origin: "vmDetails",
  1572. Code: 1000,
  1573. }
  1574. return c.JSON(http.StatusOK, resp)
  1575. //return _vmstatus.Status, _vmstatus.Name, disk, cpu, ram
  1576. }
  1577. func (o ovirt) ovirtPayment(c echo.Context) error {
  1578. invoiceUuid := c.FormValue("invoiceUuid")
  1579. db, err := sql.Open("mysql", MySQLUSER+":"+MySQLPASS+"@tcp(127.0.0.1:3306)/zicloud")
  1580. if err != nil {
  1581. }
  1582. update, err := db.Query("update scheduler set active=' 1' where related_uuid='" + invoiceUuid + "' and type=0")
  1583. defer db.Close()
  1584. if err != nil {
  1585. }
  1586. defer update.Close()
  1587. resp := _response{
  1588. Origin: "ovirt-ovirtPayment",
  1589. Message: "Done",
  1590. Code: 1000,
  1591. }
  1592. //b, _ := json.MarshalIndent(resp, "", " ")
  1593. //return c.String(http.StatusOK, string(b))
  1594. return c.JSON(http.StatusOK, resp)
  1595. }