ovirt.go 49 KB

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