ovirt.go 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680
  1. package main
  2. import (
  3. "crypto/rand"
  4. "crypto/rsa"
  5. "crypto/sha256"
  6. "crypto/tls"
  7. "crypto/x509"
  8. "database/sql"
  9. "encoding/json"
  10. "encoding/pem"
  11. "errors"
  12. "fmt"
  13. "github.com/dgrijalva/jwt-go"
  14. _ "github.com/go-sql-driver/mysql"
  15. "github.com/labstack/echo"
  16. "io/ioutil"
  17. mrand "math/rand"
  18. "net/http"
  19. "os"
  20. "strconv"
  21. "strings"
  22. "time"
  23. )
  24. type ovirt struct {
  25. }
  26. var MySQLUSER = "apigw"
  27. var MySQLPASS = "^_P+^7Q$bmPj+$xB"
  28. func login(BA string) OvirtObject {
  29. url := OvirtURL + "/ovirt-engine/api"
  30. method := "GET"
  31. client := &http.Client{}
  32. req, err := http.NewRequest(method, url, nil)
  33. if err != nil {
  34. fmt.Println(err)
  35. }
  36. req.Header.Add("Version", "4")
  37. req.Header.Add("Accept", "application/json")
  38. req.Header.Add("Authorization", BA)
  39. res, err := client.Do(req)
  40. defer res.Body.Close()
  41. body, err := ioutil.ReadAll(res.Body)
  42. object := OvirtObject{}
  43. err = json.Unmarshal(body, &object)
  44. return object
  45. }
  46. type OvirtObject struct {
  47. ProductInfo struct {
  48. Name string `json:"name"`
  49. Version struct {
  50. Build string `json:"build"`
  51. FullVersion string `json:"full_version"`
  52. Major string `json:"major"`
  53. Minor string `json:"minor"`
  54. Revision string `json:"revision"`
  55. } `json:"version"`
  56. } `json:"product_info"`
  57. SpecialObjects struct {
  58. BlankTemplate struct {
  59. Href string `json:"href"`
  60. ID string `json:"id"`
  61. } `json:"blank_template"`
  62. RootTag struct {
  63. Href string `json:"href"`
  64. ID string `json:"id"`
  65. } `json:"root_tag"`
  66. } `json:"special_objects"`
  67. Time int64 `json:"time"`
  68. AuthenticatedUser struct {
  69. Href string `json:"href"`
  70. ID string `json:"id"`
  71. } `json:"authenticated_user"`
  72. EffectiveUser struct {
  73. Href string `json:"href"`
  74. ID string `json:"id"`
  75. } `json:"effective_user"`
  76. Link []struct {
  77. Href string `json:"href"`
  78. Rel string `json:"rel"`
  79. } `json:"link"`
  80. }
  81. type TaskHeader struct {
  82. Name string `json:"Name,omitempty"`
  83. Value string `json:"Value,omitempty"`
  84. }
  85. type addVMTask struct {
  86. URL string `json:"url"`
  87. JSON string `json:__json`
  88. Method string `json:"method"`
  89. Headers []struct {
  90. Name string `json:"Name,omitempty"`
  91. Value string `json:"Value,omitempty"`
  92. } `json:"headers"`
  93. }
  94. type AddVMRequest struct {
  95. URL string `json:"url"`
  96. JSON struct {
  97. Name string `json:"name"`
  98. Description string `json:"description"`
  99. Comment string `json:"comment"`
  100. Cluster struct {
  101. Name string `json:"name"`
  102. } `json:"cluster"`
  103. Template struct {
  104. Name string `json:"name"`
  105. } `json:"template"`
  106. CPU struct {
  107. Topology struct {
  108. Sockets string `json:"sockets"`
  109. Cores string `json:"cores"`
  110. Threads string `json:"threads"`
  111. } `json:"topology"`
  112. } `json:"cpu"`
  113. Memory string `json:"memory"`
  114. MemoryPolicy struct {
  115. Ballooning string `json:"ballooning"`
  116. Guaranteed string `json:"guaranteed"`
  117. OverCommit struct {
  118. Percent string `json:"percent"`
  119. } `json:"over_commit"`
  120. } `json:"memory_policy"`
  121. } `json:"JSON"`
  122. Method string `json:"method"`
  123. Headers []struct {
  124. Name string `json:"Name"`
  125. Value string `json:"Value"`
  126. } `json:"headers"`
  127. }
  128. type VMStatistics struct {
  129. Statistic []struct {
  130. Kind string `json:"kind"`
  131. Type string `json:"type"`
  132. Unit string `json:"unit"`
  133. Values struct {
  134. Value []struct {
  135. Datum float64 `json:"datum"`
  136. } `json:"value"`
  137. } `json:"values"`
  138. VM struct {
  139. Href string `json:"href"`
  140. ID string `json:"id"`
  141. } `json:"vm,omitempty"`
  142. Name string `json:"name"`
  143. Description string `json:"description"`
  144. Href string `json:"href,omitempty"`
  145. ID string `json:"id"`
  146. } `json:"statistic"`
  147. }
  148. func (o ovirt) vmStatus(uuid string) string {
  149. type vmStatus struct {
  150. NextRunConfigurationExists string `json:"next_run_configuration_exists"`
  151. NumaTuneMode string `json:"numa_tune_mode"`
  152. Status string `json:"status"`
  153. StopTime int64 `json:"stop_time"`
  154. OriginalTemplate struct {
  155. Href string `json:"href"`
  156. ID string `json:"id"`
  157. } `json:"original_template"`
  158. Template struct {
  159. Href string `json:"href"`
  160. ID string `json:"id"`
  161. } `json:"template"`
  162. Actions struct {
  163. Link []struct {
  164. Href string `json:"href"`
  165. Rel string `json:"rel"`
  166. } `json:"link"`
  167. } `json:"actions"`
  168. Name string `json:"name"`
  169. Description string `json:"description"`
  170. Comment string `json:"comment"`
  171. Href string `json:"href"`
  172. ID string `json:"id"`
  173. Bios struct {
  174. BootMenu struct {
  175. Enabled string `json:"enabled"`
  176. } `json:"boot_menu"`
  177. Type string `json:"type"`
  178. } `json:"bios"`
  179. CPU struct {
  180. Architecture string `json:"architecture"`
  181. Topology struct {
  182. Cores string `json:"cores"`
  183. Sockets string `json:"sockets"`
  184. Threads string `json:"threads"`
  185. } `json:"topology"`
  186. } `json:"cpu"`
  187. Display struct {
  188. AllowOverride string `json:"allow_override"`
  189. CopyPasteEnabled string `json:"copy_paste_enabled"`
  190. DisconnectAction string `json:"disconnect_action"`
  191. FileTransferEnabled string `json:"file_transfer_enabled"`
  192. Monitors string `json:"monitors"`
  193. SingleQxlPci string `json:"single_qxl_pci"`
  194. SmartcardEnabled string `json:"smartcard_enabled"`
  195. Type string `json:"type"`
  196. } `json:"display"`
  197. Initialization struct {
  198. AuthorizedSSHKeys string `json:"authorized_ssh_keys"`
  199. CloudInitNetworkProtocol string `json:"cloud_init_network_protocol"`
  200. CustomScript string `json:"custom_script"`
  201. HostName string `json:"host_name"`
  202. NicConfigurations struct {
  203. } `json:"nic_configurations"`
  204. RegenerateSSHKeys string `json:"regenerate_ssh_keys"`
  205. UserName string `json:"user_name"`
  206. } `json:"initialization"`
  207. Io struct {
  208. Threads string `json:"threads"`
  209. } `json:"io"`
  210. Memory string `json:"memory"`
  211. Migration struct {
  212. AutoConverge string `json:"auto_converge"`
  213. Compressed string `json:"compressed"`
  214. Encrypted string `json:"encrypted"`
  215. } `json:"migration"`
  216. Origin string `json:"origin"`
  217. Os struct {
  218. Boot struct {
  219. Devices struct {
  220. Device []string `json:"device"`
  221. } `json:"devices"`
  222. } `json:"boot"`
  223. Type string `json:"type"`
  224. } `json:"os"`
  225. Sso struct {
  226. Methods struct {
  227. Method []struct {
  228. ID string `json:"id"`
  229. } `json:"method"`
  230. } `json:"methods"`
  231. } `json:"sso"`
  232. Stateless string `json:"stateless"`
  233. Type string `json:"type"`
  234. Usb struct {
  235. Enabled string `json:"enabled"`
  236. } `json:"usb"`
  237. Cluster struct {
  238. Href string `json:"href"`
  239. ID string `json:"id"`
  240. } `json:"cluster"`
  241. Quota struct {
  242. ID string `json:"id"`
  243. } `json:"quota"`
  244. Link []struct {
  245. Href string `json:"href"`
  246. Rel string `json:"rel"`
  247. } `json:"link"`
  248. CPUShares string `json:"cpu_shares"`
  249. CreationTime int64 `json:"creation_time"`
  250. DeleteProtected string `json:"delete_protected"`
  251. HighAvailability struct {
  252. Enabled string `json:"enabled"`
  253. Priority string `json:"priority"`
  254. } `json:"high_availability"`
  255. LargeIcon struct {
  256. Href string `json:"href"`
  257. ID string `json:"id"`
  258. } `json:"large_icon"`
  259. MemoryPolicy struct {
  260. Ballooning string `json:"ballooning"`
  261. Guaranteed string `json:"guaranteed"`
  262. Max string `json:"max"`
  263. } `json:"memory_policy"`
  264. MigrationDowntime string `json:"migration_downtime"`
  265. MultiQueuesEnabled string `json:"multi_queues_enabled"`
  266. PlacementPolicy struct {
  267. Affinity string `json:"affinity"`
  268. Hosts struct {
  269. Host []struct {
  270. Href string `json:"href"`
  271. ID string `json:"id"`
  272. } `json:"host"`
  273. } `json:"hosts"`
  274. } `json:"placement_policy"`
  275. SmallIcon struct {
  276. Href string `json:"href"`
  277. ID string `json:"id"`
  278. } `json:"small_icon"`
  279. StartPaused string `json:"start_paused"`
  280. StorageErrorResumeBehaviour string `json:"storage_error_resume_behaviour"`
  281. TimeZone struct {
  282. Name string `json:"name"`
  283. } `json:"time_zone"`
  284. CPUProfile struct {
  285. Href string `json:"href"`
  286. ID string `json:"id"`
  287. } `json:"cpu_profile"`
  288. }
  289. //url := "https://ovirt-cl.zi-tel.com/ovirt-engine/api/vms/c1a44128-6c6c-406b-99d8-4a68a99380c9"
  290. url := OvirtURL + "/ovirt-engine/api/vms/" + uuid
  291. //fmt.Println("VMSTATUS UUID:" ,uuid)
  292. method := "GET"
  293. client := &http.Client{}
  294. req, err := http.NewRequest(method, url, nil)
  295. if err != nil {
  296. fmt.Println("Error in vmStatus ", err)
  297. //return "Null"
  298. }
  299. req.Header.Add("Version", "4")
  300. req.Header.Add("Accept", "application/json")
  301. //fmt.Println("in vmStatus 1 " )
  302. //TODO: replace BA
  303. req.Header.Add("Authorization", "Basic YWRtaW5AaW50ZXJuYWw6a2VsYW5zaCBqMw==")
  304. //fmt.Println("in vmStatus 1 2 " )
  305. res, err := client.Do(req)
  306. //fmt.Println("in vmStatus :",err )
  307. if err != nil {
  308. fmt.Println("Error in vmStatus ", err)
  309. //return "Null"
  310. }
  311. defer res.Body.Close()
  312. //fmt.Println("in vmStatus 3 " )
  313. body, err := ioutil.ReadAll(res.Body)
  314. if err != nil {
  315. fmt.Println("Error in vmStatus ", err)
  316. //return "Null"
  317. }
  318. //fmt.Println("full response: ",string(body))
  319. //fmt.Println("in vmStatus 4 " )
  320. _vmstatus := vmStatus{}
  321. _err := json.Unmarshal(body, &_vmstatus)
  322. //fmt.Println("in vmStatus 5 " )
  323. if _err != nil {
  324. fmt.Println("Error in vmStatus ", _err)
  325. }
  326. return _vmstatus.Status
  327. }
  328. func (o ovirt) addvm(c echo.Context) error {
  329. type AddVMPayment struct {
  330. Data struct {
  331. Price struct {
  332. CPU float64 `json:"cpu"`
  333. Mem float64 `json:"mem"`
  334. Disk float64 `json:"disk"`
  335. Nic float64 `json:"nic"`
  336. BW float64 `json:"bw"`
  337. SUM float64 `json:"sum"`
  338. Period string `json:"period"`
  339. } `json:"price"`
  340. InvoiceUUID string `json:"invoiceUUID"`
  341. } `json:"data"`
  342. Message string `json:"message"`
  343. Origin string `json:"origin"`
  344. Code int `json:"code"`
  345. }
  346. user := c.Get("user").(*jwt.Token)
  347. claims := user.Claims.(jwt.MapClaims)
  348. _sha256 := sha256.Sum256([]byte(string(claims["name"].(string))))
  349. var hashChannel_ = make(chan []byte, 1)
  350. hashChannel_ <- _sha256[:]
  351. token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
  352. _BA := strings.Split(token, ";")
  353. BA := _BA[len(_BA)-2]
  354. var vmname, vmdescr, vmcomment, templatename, cpuSock, cpuCore, cpuThread, mem, Disk, nic, period, extraBW string
  355. vmname = login(BA).AuthenticatedUser.ID + "-_-" + c.FormValue("VmName")
  356. vmdescr = c.FormValue("VmDescr")
  357. vmcomment = c.FormValue("VmComment")
  358. templatename = c.FormValue("VmTempl")
  359. cpuThread = c.FormValue("VmCPU")
  360. Disk = c.FormValue("VmDisk")
  361. period = c.FormValue("VmPeriod")
  362. nic = c.FormValue("VmNIC")
  363. extraBW = c.FormValue("extraBW")
  364. sshKey := c.FormValue("sshKey")
  365. rootpass := c.FormValue("rootpass")
  366. cpuCore = "1"
  367. cpuSock = "1"
  368. mem = c.FormValue("VmMem")
  369. url := OvirtURL + "/ovirt-engine/api/vms"
  370. method := "POST"
  371. //TODO: Encrypt this Json
  372. // _json := fmt.Sprintf(`
  373. //{
  374. // "name": "%s",
  375. // "description": "%s",
  376. // "comment": "%s",
  377. // "cluster": {
  378. // "name": "Default"
  379. // },
  380. // "template": {
  381. // "name": "%s"
  382. // },
  383. // "cpu": {
  384. // "topology": {
  385. // "sockets": "%s",
  386. // "cores": "%s",
  387. // "threads": "%s"
  388. // }
  389. // },
  390. // "memory": "%s",
  391. // "memory_policy": {
  392. // "ballooning": "true",
  393. // "guaranteed": "%s",
  394. // "over_commit": {
  395. // "percent": "10"
  396. // }
  397. // }
  398. //}
  399. //`, vmname, vmdescr, vmcomment, templatename, cpuSock, cpuCore, cpuThread, mem, mem)
  400. // Change as task
  401. //change to task// payload := strings.NewReader(_json)
  402. //change to task// //tr := &http.Transport{
  403. //change to task// // TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  404. //change to task// //}
  405. //change to task// client := &http.Client{}
  406. //change to task// req, err := http.NewRequest(method, url, payload)
  407. //change to task// if err != nil {
  408. //change to task// fmt.Println(err)
  409. //change to task// }
  410. //change to task// req.Header.Add("Version", "4")
  411. //change to task// req.Header.Add("Accept", "application/json")
  412. //change to task// req.Header.Add("Authorization", BA)
  413. //change to task// req.Header.Add("Content-Type", "application/json")
  414. //change to task// res, err := client.Do(req)
  415. //change to task// body, err := ioutil.ReadAll(res.Body)
  416. //change to task// //fmt.Println("len: ", len(_json))
  417. //change to task// //fmt.Println("res:", res)
  418. //change to task// if err != nil || res.StatusCode != 202 {
  419. //change to task// resp := _response{
  420. //change to task// Origin: "ovirt-addvm",
  421. //change to task// Message: res.Status,
  422. //change to task// Code: 1001,
  423. //change to task// }
  424. //change to task// b, _ := json.MarshalIndent(resp, "", " ")
  425. //change to task// return c.String(http.StatusBadRequest, string(b))
  426. //change to task// }
  427. //change to task// defer res.Body.Close()
  428. //addvmresponse := AddVMResponse{}O
  429. newvm := AddVMRequest{
  430. URL: url,
  431. JSON: struct {
  432. Name string `json:"name"`
  433. Description string `json:"description"`
  434. Comment string `json:"comment"`
  435. Cluster struct {
  436. Name string `json:"name"`
  437. } `json:"cluster"`
  438. Template struct {
  439. Name string `json:"name"`
  440. } `json:"template"`
  441. CPU struct {
  442. Topology struct {
  443. Sockets string `json:"sockets"`
  444. Cores string `json:"cores"`
  445. Threads string `json:"threads"`
  446. } `json:"topology"`
  447. } `json:"cpu"`
  448. Memory string `json:"memory"`
  449. MemoryPolicy struct {
  450. Ballooning string `json:"ballooning"`
  451. Guaranteed string `json:"guaranteed"`
  452. OverCommit struct {
  453. Percent string `json:"percent"`
  454. } `json:"over_commit"`
  455. } `json:"memory_policy"`
  456. }{
  457. Name: vmname,
  458. Description: vmdescr,
  459. Comment: vmcomment,
  460. Cluster: struct {
  461. Name string `json:"name"`
  462. }{Name: "Default"},
  463. Template: struct {
  464. Name string `json:"name"`
  465. }{Name: templatename},
  466. CPU: struct {
  467. Topology struct {
  468. Sockets string `json:"sockets"`
  469. Cores string `json:"cores"`
  470. Threads string `json:"threads"`
  471. } `json:"topology"`
  472. }{
  473. struct {
  474. Sockets string `json:"sockets"`
  475. Cores string `json:"cores"`
  476. Threads string `json:"threads"`
  477. }{
  478. Sockets: cpuSock,
  479. Cores: cpuCore,
  480. Threads: cpuThread,
  481. },
  482. },
  483. Memory: mem,
  484. MemoryPolicy: struct {
  485. Ballooning string `json:"ballooning"`
  486. Guaranteed string `json:"guaranteed"`
  487. OverCommit struct {
  488. Percent string `json:"percent"`
  489. } `json:"over_commit"`
  490. }{
  491. Ballooning: "true",
  492. Guaranteed: mem,
  493. OverCommit: struct {
  494. Percent string `json:"percent"`
  495. }{Percent: "10"},
  496. },
  497. },
  498. Method: method,
  499. Headers: nil,
  500. }
  501. newvm.Headers = append(newvm.Headers, struct {
  502. Name string `json:"Name"`
  503. Value string `json:"Value"`
  504. }{
  505. Name: "Accept",
  506. Value: "application/json",
  507. })
  508. newvm.Headers = append(newvm.Headers, struct {
  509. Name string `json:"Name"`
  510. Value string `json:"Value"`
  511. }{
  512. Name: "Authorization",
  513. Value: BA,
  514. })
  515. newvm.Headers = append(newvm.Headers, struct {
  516. Name string `json:"Name"`
  517. Value string `json:"Value"`
  518. }{
  519. Name: "Content-Type",
  520. Value: "application/json",
  521. })
  522. uuid, _ := uuidgen("APIGW-Ovirt-addVMTask")
  523. //invoiceUUID, _ := uuidgen("APIGW-FakeInvoice")
  524. CPUPrice, memPrice, StoragePrice, IPPrice, extraBWPrice, SUM, invoiceUUID := IaaSCreate(login(BA).AuthenticatedUser.ID, period, cpuThread, mem, Disk, nic, extraBW)
  525. responseInvoiece := AddVMPayment{
  526. Data: struct {
  527. Price struct {
  528. CPU float64 `json:"cpu"`
  529. Mem float64 `json:"mem"`
  530. Disk float64 `json:"disk"`
  531. Nic float64 `json:"nic"`
  532. BW float64 `json:"bw"`
  533. SUM float64 `json:"sum"`
  534. Period string `json:"period"`
  535. } `json:"price"`
  536. InvoiceUUID string `json:"invoiceUUID"`
  537. }{
  538. Price: struct {
  539. CPU float64 `json:"cpu"`
  540. Mem float64 `json:"mem"`
  541. Disk float64 `json:"disk"`
  542. Nic float64 `json:"nic"`
  543. BW float64 `json:"bw"`
  544. SUM float64 `json:"sum"`
  545. Period string `json:"period"`
  546. }{
  547. CPU: CPUPrice,
  548. Mem: memPrice,
  549. Disk: StoragePrice,
  550. Nic: IPPrice,
  551. BW: extraBWPrice,
  552. SUM: SUM,
  553. Period: period,
  554. },
  555. InvoiceUUID: invoiceUUID,
  556. },
  557. Message: "Done",
  558. Origin: "AddVM",
  559. Code: 1000,
  560. }
  561. if len(invoiceUUID) < 5 {
  562. resp := _response{
  563. Origin: "ovirt-addvm",
  564. Message: "Error on Invoice Calculation",
  565. Code: 1001,
  566. }
  567. b, _ := json.MarshalIndent(resp, "", " ")
  568. return c.String(http.StatusBadRequest, string(b))
  569. }
  570. //fmt.Println("Invoice: ",invoiceUUID)
  571. __createVM, _ := json.MarshalIndent(newvm, "", " ")
  572. // Add VM Task
  573. addTask(uuid, string(__createVM), "", "APIGW", "VM Creation for "+claims["name"].(string), invoiceUUID, "0", "0")
  574. {
  575. db, err := sql.Open("mysql", MySQLUSER+":"+MySQLPASS+"@tcp(127.0.0.1:3306)/zicloud")
  576. if err != nil {
  577. resp := _response{
  578. Origin: "ovirt-addvm",
  579. Message: "Error on connecting db for save add vm result",
  580. Code: 1001,
  581. }
  582. b, _ := json.MarshalIndent(resp, "", " ")
  583. return c.String(http.StatusBadRequest, string(b))
  584. }
  585. defer db.Close()
  586. insert, err := db.Query("INSERT INTO service_profile VALUES ( '" + invoiceUUID + "'," +
  587. "'" + claims["IPAUid"].(string) + "'," +
  588. "'" + "VM" + "'," +
  589. "'" + "" + "'," +
  590. "'" + login(BA).AuthenticatedUser.ID + "'," +
  591. "NOW()" + "," +
  592. "NOW() ," +
  593. "-1" + "," +
  594. "'" + vmname + "'," +
  595. "'" + invoiceUUID + "' )")
  596. defer insert.Close()
  597. if err != nil {
  598. fmt.Println("Error in addVM: ", err.Error())
  599. }
  600. }
  601. // Start Task
  602. {
  603. url := OvirtURL + "/ovirt-engine/api/vms/" + invoiceUUID + "/start"
  604. method := "POST"
  605. nicAddress := "172.20.15.251"
  606. nicMask := "255.255.255.0"
  607. nicGW := "172.20.15.1"
  608. __json := fmt.Sprintf(`
  609. {
  610. "async":"true",
  611. "use_cloud_init": "true",
  612. "vm": {
  613. "initialization": {
  614. "authorized_ssh_keys": "%s",
  615. "host_name": "Sassan.local",
  616. "user_name": "root",
  617. "root_password": "%s",
  618. "nic_configurations": {
  619. "nic_configuration": [
  620. {
  621. "name": "eth0",
  622. "on_boot": "true",
  623. "boot_protocol": "static",
  624. "ip": {
  625. "address": "%s",
  626. "netmask": "%s",
  627. "gateway": "%s"
  628. }
  629. }
  630. ]
  631. },
  632. "dns_servers": "172.20.11.11"
  633. }
  634. }
  635. }
  636. `, sshKey, rootpass, nicAddress, nicMask, nicGW)
  637. sha256 := sha256.Sum256([]byte(invoiceUUID))
  638. var hashChannel = make(chan []byte, 1)
  639. hashChannel <- sha256[:]
  640. ___json := encrypt(<-hashChannel, __json)
  641. startVM := addVMTask{
  642. URL: url,
  643. JSON: ___json,
  644. Method: method,
  645. Headers: nil,
  646. }
  647. startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Version", Value: "4"})
  648. startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Accept", Value: "application/json"})
  649. startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Content-Type", Value: "application/json"})
  650. startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Authorization", Value: BA})
  651. uuid, _ := uuidgen("APIGW-Ovirt-CloudInit")
  652. __startVM, _ := json.MarshalIndent(startVM, "", " ")
  653. //fmt.Println("StartVMHeaders: ", string(__startVMHeaders))
  654. addTask(uuid, string(__startVM), "", "APIGW", "VM Initialization", invoiceUUID, "1", "0")
  655. }
  656. //resp := _response{
  657. // Origin: "ovirt-addvm",
  658. // Message: resposeInvoice
  659. // Code: 1000,
  660. //}
  661. return c.JSON(http.StatusOK, responseInvoiece)
  662. }
  663. func (o ovirt) listVM(c echo.Context) error {
  664. type listVMs struct {
  665. VM []struct {
  666. Fqdn string `json:"fqdn,omitempty"`
  667. GuestOperatingSystem struct {
  668. Architecture string `json:"architecture"`
  669. Codename string `json:"codename"`
  670. Distribution string `json:"distribution"`
  671. Family string `json:"family"`
  672. Kernel struct {
  673. Version struct {
  674. Build string `json:"build"`
  675. FullVersion string `json:"full_version"`
  676. Major string `json:"major"`
  677. Minor string `json:"minor"`
  678. Revision string `json:"revision"`
  679. } `json:"version"`
  680. } `json:"kernel"`
  681. Version struct {
  682. FullVersion string `json:"full_version"`
  683. Major string `json:"major"`
  684. } `json:"version"`
  685. } `json:"guest_operating_system,omitempty"`
  686. GuestTimeZone struct {
  687. Name string `json:"name"`
  688. UtcOffset string `json:"utc_offset"`
  689. } `json:"guest_time_zone,omitempty"`
  690. NextRunConfigurationExists string `json:"next_run_configuration_exists"`
  691. NumaTuneMode string `json:"numa_tune_mode"`
  692. RunOnce string `json:"run_once,omitempty"`
  693. StartTime int64 `json:"start_time,omitempty"`
  694. Status string `json:"status"`
  695. StopTime int64 `json:"stop_time"`
  696. OriginalTemplate struct {
  697. Href string `json:"href"`
  698. ID string `json:"id"`
  699. } `json:"original_template"`
  700. Template struct {
  701. Href string `json:"href"`
  702. ID string `json:"id"`
  703. } `json:"template"`
  704. Actions struct {
  705. Link []struct {
  706. Href string `json:"href"`
  707. Rel string `json:"rel"`
  708. } `json:"link"`
  709. } `json:"actions"`
  710. Name string `json:"name"`
  711. Description string `json:"description"`
  712. Comment string `json:"comment"`
  713. Href string `json:"href"`
  714. ID string `json:"id"`
  715. Bios struct {
  716. BootMenu struct {
  717. Enabled string `json:"enabled"`
  718. } `json:"boot_menu"`
  719. Type string `json:"type"`
  720. } `json:"bios"`
  721. CPU struct {
  722. Architecture string `json:"architecture"`
  723. Topology struct {
  724. Cores string `json:"cores"`
  725. Sockets string `json:"sockets"`
  726. Threads string `json:"threads"`
  727. } `json:"topology"`
  728. } `json:"cpu"`
  729. Display struct {
  730. Address string `json:"address"`
  731. AllowOverride string `json:"allow_override"`
  732. Certificate struct {
  733. Content string `json:"content"`
  734. Organization string `json:"organization"`
  735. Subject string `json:"subject"`
  736. } `json:"certificate"`
  737. CopyPasteEnabled string `json:"copy_paste_enabled"`
  738. DisconnectAction string `json:"disconnect_action"`
  739. FileTransferEnabled string `json:"file_transfer_enabled"`
  740. Monitors string `json:"monitors"`
  741. Port string `json:"port"`
  742. SecurePort string `json:"secure_port"`
  743. SingleQxlPci string `json:"single_qxl_pci"`
  744. SmartcardEnabled string `json:"smartcard_enabled"`
  745. Type string `json:"type"`
  746. } `json:"display"`
  747. Initialization struct {
  748. AuthorizedSSHKeys string `json:"authorized_ssh_keys"`
  749. CloudInitNetworkProtocol string `json:"cloud_init_network_protocol"`
  750. CustomScript string `json:"custom_script"`
  751. HostName string `json:"host_name"`
  752. NicConfigurations struct {
  753. } `json:"nic_configurations"`
  754. RegenerateSSHKeys string `json:"regenerate_ssh_keys"`
  755. UserName string `json:"user_name"`
  756. } `json:"initialization"`
  757. Io struct {
  758. Threads string `json:"threads"`
  759. } `json:"io"`
  760. Memory string `json:"memory"`
  761. Migration struct {
  762. AutoConverge string `json:"auto_converge"`
  763. Compressed string `json:"compressed"`
  764. Encrypted string `json:"encrypted"`
  765. } `json:"migration"`
  766. Origin string `json:"origin"`
  767. Os struct {
  768. Boot struct {
  769. Devices struct {
  770. Device []string `json:"device"`
  771. } `json:"devices"`
  772. } `json:"boot"`
  773. Type string `json:"type"`
  774. } `json:"os"`
  775. Sso struct {
  776. Methods struct {
  777. Method []struct {
  778. ID string `json:"id"`
  779. } `json:"method"`
  780. } `json:"methods"`
  781. } `json:"sso"`
  782. Stateless string `json:"stateless"`
  783. Type string `json:"type"`
  784. Usb struct {
  785. Enabled string `json:"enabled"`
  786. } `json:"usb"`
  787. Cluster struct {
  788. Href string `json:"href"`
  789. ID string `json:"id"`
  790. } `json:"cluster"`
  791. Quota struct {
  792. ID string `json:"id"`
  793. } `json:"quota"`
  794. Link []struct {
  795. Href string `json:"href"`
  796. Rel string `json:"rel"`
  797. } `json:"link"`
  798. CPUShares string `json:"cpu_shares"`
  799. CreationTime int64 `json:"creation_time"`
  800. DeleteProtected string `json:"delete_protected"`
  801. HighAvailability struct {
  802. Enabled string `json:"enabled"`
  803. Priority string `json:"priority"`
  804. } `json:"high_availability"`
  805. LargeIcon struct {
  806. Href string `json:"href"`
  807. ID string `json:"id"`
  808. } `json:"large_icon"`
  809. MemoryPolicy struct {
  810. Guaranteed string `json:"guaranteed"`
  811. Max string `json:"max"`
  812. } `json:"memory_policy"`
  813. MigrationDowntime string `json:"migration_downtime"`
  814. MultiQueuesEnabled string `json:"multi_queues_enabled"`
  815. SmallIcon struct {
  816. Href string `json:"href"`
  817. ID string `json:"id"`
  818. } `json:"small_icon"`
  819. StartPaused string `json:"start_paused"`
  820. StorageErrorResumeBehaviour string `json:"storage_error_resume_behaviour"`
  821. TimeZone struct {
  822. Name string `json:"name"`
  823. } `json:"time_zone"`
  824. CPUProfile struct {
  825. Href string `json:"href"`
  826. ID string `json:"id"`
  827. } `json:"cpu_profile"`
  828. StopReason string `json:"stop_reason,omitempty"`
  829. } `json:"vm"`
  830. }
  831. type listVMResponse struct {
  832. Data []struct {
  833. Fqdn string `json:"fqdn"`
  834. StartTime int64 `json:"start_time"`
  835. Status string `json:"status"`
  836. Name string `json:"name"`
  837. Description string `json:"description"`
  838. Comment string `json:"comment"`
  839. ID string `json:"id"`
  840. CPU struct {
  841. Topology struct {
  842. Cores string `json:"cores"`
  843. Sockets string `json:"sockets"`
  844. Threads string `json:"threads"`
  845. } `json:"topology"`
  846. } `json:"cpu"`
  847. Memory string `json:"memory"`
  848. CreationTime int64 `json:"creation_time"`
  849. Disk []struct {
  850. Name string `json:"Name"`
  851. TotalSize string `json:"TotalSize"`
  852. ActualSize string `json:"ActualSize"`
  853. } `json:"Disk"`
  854. NIC []struct {
  855. Mac string `json:"mac"`
  856. IPv4 string `json:"IPv4"`
  857. IPv6 string `json:"IPv6"`
  858. ReportedDevices struct {
  859. Mac string `json:"mac"`
  860. IPv4 string `json:"IPv4"`
  861. IPv6 string `json:"IPv6"`
  862. } `json:"reported_devices"`
  863. } `json:"NIC"`
  864. } `json:"vm"`
  865. Message string `json:"message"`
  866. Origin string `json:"origin"`
  867. Code int `json:"code"`
  868. }
  869. user := c.Get("user").(*jwt.Token)
  870. claims := user.Claims.(jwt.MapClaims)
  871. _sha256 := sha256.Sum256([]byte(string(claims["name"].(string))))
  872. var hashChannel_ = make(chan []byte, 1)
  873. hashChannel_ <- _sha256[:]
  874. token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
  875. _BA := strings.Split(token, ";")
  876. BA := _BA[len(_BA)-2]
  877. url := OvirtURL + "/ovirt-engine/api/vms"
  878. client := &http.Client{}
  879. req, err := http.NewRequest("GET", url, nil)
  880. if err != nil {
  881. fmt.Println(err)
  882. }
  883. req.Header.Add("Version", "4")
  884. req.Header.Add("Accept", "application/json")
  885. req.Header.Add("Authorization", BA)
  886. res, err := client.Do(req)
  887. defer res.Body.Close()
  888. body, err := ioutil.ReadAll(res.Body)
  889. //fmt.Printf("%s",body)
  890. //b, _ := json.MarshalIndent(body, "", " ")
  891. _VMLists := listVMs{}
  892. err = json.Unmarshal(body, &_VMLists)
  893. _listVMResponse := listVMResponse{
  894. Data: nil,
  895. Message: "Done",
  896. Origin: "ListVMs",
  897. Code: 1000,
  898. }
  899. _Data := _listVMResponse.Data
  900. y := struct {
  901. Fqdn string `json:"fqdn"`
  902. StartTime int64 `json:"start_time"`
  903. Status string `json:"status"`
  904. Name string `json:"name"`
  905. Description string `json:"description"`
  906. Comment string `json:"comment"`
  907. ID string `json:"id"`
  908. CPU struct {
  909. Topology struct {
  910. Cores string `json:"cores"`
  911. Sockets string `json:"sockets"`
  912. Threads string `json:"threads"`
  913. } `json:"topology"`
  914. } `json:"cpu"`
  915. Memory string `json:"memory"`
  916. CreationTime int64 `json:"creation_time"`
  917. Disk []struct {
  918. Name string `json:"Name"`
  919. TotalSize string `json:"TotalSize"`
  920. ActualSize string `json:"ActualSize"`
  921. } `json:"Disk"`
  922. NIC []struct {
  923. Mac string `json:"mac"`
  924. IPv4 string `json:"IPv4"`
  925. IPv6 string `json:"IPv6"`
  926. ReportedDevices struct {
  927. Mac string `json:"mac"`
  928. IPv4 string `json:"IPv4"`
  929. IPv6 string `json:"IPv6"`
  930. } `json:"reported_devices"`
  931. } `json:"NIC"`
  932. }{}
  933. //fmt.Println("Customer UUID:",login(BA).AuthenticatedUser.ID)
  934. for _, v := range _VMLists.VM {
  935. y.ID = v.ID
  936. y.Fqdn = v.Fqdn
  937. y.StartTime = v.StartTime
  938. y.Status = v.Status
  939. y.Name = v.Name
  940. if len(v.Name) > 35 {
  941. y.Name = v.Name[len(login(BA).AuthenticatedUser.ID)+3:]
  942. }
  943. y.Description = v.Description
  944. y.Comment = v.Comment
  945. y.CPU.Topology.Cores = v.CPU.Topology.Cores
  946. y.CPU.Topology.Sockets = v.CPU.Topology.Sockets
  947. y.CPU.Topology.Threads = v.CPU.Topology.Threads
  948. y.Memory = v.Memory
  949. y.CreationTime = v.CreationTime
  950. y.NIC = listNIC(v.ID, BA)
  951. y.Disk = listDisks(v.ID, BA)
  952. _Data = append(_Data, y)
  953. }
  954. _listVMResponse.Data = _Data
  955. if err != nil {
  956. //fmt.Println("Error on ListVM",err)
  957. //return CPUPrice, memPrice, StoragePrice, IPPrice, extraBWPrice
  958. resp := _response{
  959. Origin: "ovirt-listvms",
  960. Message: "Error in Parsing listVMs",
  961. Code: 1001,
  962. }
  963. return c.JSON(http.StatusInternalServerError, resp)
  964. }
  965. //fmt.Printf("%s", body)
  966. //b, _ := json.MarshalIndent(resp, "", " ")
  967. return c.JSON(http.StatusOK, _listVMResponse)
  968. //return c.String(http.StatusOK, string(b))
  969. }
  970. func (o ovirt) StartVM(c echo.Context) error {
  971. vmuuid := c.FormValue("VmUUID")
  972. user := c.Get("user").(*jwt.Token)
  973. claims := user.Claims.(jwt.MapClaims)
  974. _sha256 := sha256.Sum256([]byte(string(claims["name"].(string))))
  975. var hashChannel_ = make(chan []byte, 1)
  976. hashChannel_ <- _sha256[:]
  977. token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
  978. _BA := strings.Split(token, ";")
  979. BA := _BA[len(_BA)-2]
  980. url := OvirtURL + "/ovirt-engine/api/vms/" + vmuuid + "/start"
  981. method := "POST"
  982. __json := "{\"async\":\"true\"}"
  983. sha256 := sha256.Sum256([]byte(vmuuid))
  984. var hashChannel = make(chan []byte, 1)
  985. hashChannel <- sha256[:]
  986. ___json := encrypt(<-hashChannel, __json)
  987. startVM := addVMTask{
  988. URL: url,
  989. JSON: ___json,
  990. Method: method,
  991. Headers: nil,
  992. }
  993. startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Version", Value: "4"})
  994. startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Accept", Value: "application/json"})
  995. startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Content-Type", Value: "application/json"})
  996. startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Authorization", Value: BA})
  997. //req.Header.Add("Version", "4")
  998. //req.Header.Add("Accept", "application/json")
  999. //req.Header.Add("Authorization", BA)
  1000. //req.Header.Add("Content-Type", "application/json")
  1001. //
  1002. //res, err := client.Do(req)
  1003. //defer res.Body.Close()
  1004. uuid, _ := uuidgen("APIGW-Ovirt")
  1005. __startVM, _ := json.MarshalIndent(startVM, "", " ")
  1006. //fmt.Println("StartVMHeaders: ", string(__startVMHeaders))
  1007. addTask(uuid, string(__startVM), "", "APIGW", "VM Start", vmuuid, "1", "1")
  1008. resp := _response{
  1009. Origin: "ovirt-StartVM",
  1010. Message: "Done",
  1011. Code: 1000,
  1012. }
  1013. //b, _ := json.MarshalIndent(resp, "", " ")
  1014. return c.JSON(http.StatusOK, resp)
  1015. //return c.String(http.StatusOK, string(b))
  1016. }
  1017. func (o ovirt) StopVM(c echo.Context) error {
  1018. vmuuid := c.FormValue("VmUUID")
  1019. user := c.Get("user").(*jwt.Token)
  1020. claims := user.Claims.(jwt.MapClaims)
  1021. _sha256 := sha256.Sum256([]byte(string(claims["name"].(string))))
  1022. var hashChannel_ = make(chan []byte, 1)
  1023. hashChannel_ <- _sha256[:]
  1024. token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
  1025. _BA := strings.Split(token, ";")
  1026. BA := _BA[len(_BA)-2]
  1027. url := OvirtURL + "/ovirt-engine/api/vms/" + vmuuid + "/shutdown"
  1028. method := "POST"
  1029. __json := "{\"async\":\"true\"}"
  1030. sha256 := sha256.Sum256([]byte(vmuuid))
  1031. var hashChannel = make(chan []byte, 1)
  1032. hashChannel <- sha256[:]
  1033. ___json := encrypt(<-hashChannel, __json)
  1034. payload := strings.NewReader(___json)
  1035. tr := &http.Transport{
  1036. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  1037. }
  1038. client := &http.Client{Transport: tr}
  1039. req, err := http.NewRequest(method, url, payload)
  1040. if err != nil {
  1041. fmt.Println(err)
  1042. }
  1043. req.Header.Add("Version", "4")
  1044. req.Header.Add("Accept", "application/json")
  1045. req.Header.Add("Authorization", BA)
  1046. res, err := client.Do(req)
  1047. if err != nil {
  1048. //return c.String(http.StatusBadRequest, "Error"+err.Error())
  1049. return c.JSON(http.StatusOK, "Error"+err.Error())
  1050. }
  1051. defer res.Body.Close()
  1052. body, err := ioutil.ReadAll(res.Body)
  1053. fmt.Println("Resp:" + string(body))
  1054. //req.Header.Add("Version", "4")
  1055. //req.Header.Add("Accept", "application/json")
  1056. //req.Header.Add("Authorization", BA)
  1057. //req.Header.Add("Content-Type", "application/json")
  1058. //
  1059. //res, err := client.Do(req)
  1060. //defer res.Body.Close()
  1061. //uuid, _ := uuidgen("APIGW-Ovirt")
  1062. //__startVM, _ := json.MarshalIndent(req, "", " ")
  1063. //fmt.Println("StartVMHeaders: ", string(__startVMHeaders))
  1064. //addTask(uuid, string(__startVM), "", "APIGW", "VM Start", vmuuid, "1", "1")
  1065. resp := _response{
  1066. Origin: "ovirt-StopVM",
  1067. Message: "Done",
  1068. Code: 1000,
  1069. }
  1070. //b, _ := json.MarshalIndent(resp, "", " ")
  1071. return c.JSON(http.StatusOK, resp)
  1072. //return c.String(http.StatusOK, string(b))
  1073. }
  1074. func (o ovirt) RebootVM(c echo.Context) error {
  1075. vmuuid := c.FormValue("VmUUID")
  1076. user := c.Get("user").(*jwt.Token)
  1077. claims := user.Claims.(jwt.MapClaims)
  1078. _sha256 := sha256.Sum256([]byte(string(claims["name"].(string))))
  1079. var hashChannel_ = make(chan []byte, 1)
  1080. hashChannel_ <- _sha256[:]
  1081. token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
  1082. _BA := strings.Split(token, ";")
  1083. BA := _BA[len(_BA)-2]
  1084. url := OvirtURL + "/ovirt-engine/api/vms/" + vmuuid + "/reboot"
  1085. method := "POST"
  1086. __json := "{\"async\":\"true\"}"
  1087. sha256 := sha256.Sum256([]byte(vmuuid))
  1088. var hashChannel = make(chan []byte, 1)
  1089. hashChannel <- sha256[:]
  1090. ___json := encrypt(<-hashChannel, __json)
  1091. startVM := addVMTask{
  1092. URL: url,
  1093. JSON: ___json,
  1094. Method: method,
  1095. Headers: nil,
  1096. }
  1097. startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Version", Value: "4"})
  1098. startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Accept", Value: "application/json"})
  1099. startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Content-Type", Value: "application/json"})
  1100. startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Authorization", Value: BA})
  1101. //req.Header.Add("Version", "4")
  1102. //req.Header.Add("Accept", "application/json")
  1103. //req.Header.Add("Authorization", BA)
  1104. //req.Header.Add("Content-Type", "application/json")
  1105. //
  1106. //res, err := client.Do(req)
  1107. //defer res.Body.Close()
  1108. uuid, _ := uuidgen("APIGW-Ovirt")
  1109. __startVM, _ := json.MarshalIndent(startVM, "", " ")
  1110. //fmt.Println("StartVMHeaders: ", string(__startVMHeaders))
  1111. addTask(uuid, string(__startVM), "", "APIGW", "VM Start", vmuuid, "1", "1")
  1112. resp := _response{
  1113. Origin: "ovirt-RebootVM",
  1114. Message: "Done",
  1115. Code: 1000,
  1116. }
  1117. //b, _ := json.MarshalIndent(resp, "", " ")
  1118. //return c.String(http.StatusOK, string(b))
  1119. return c.JSON(http.StatusOK, resp)
  1120. }
  1121. func (o ovirt) PowerOffVM(c echo.Context) error {
  1122. vmuuid := c.FormValue("VmUUID")
  1123. user := c.Get("user").(*jwt.Token)
  1124. claims := user.Claims.(jwt.MapClaims)
  1125. _sha256 := sha256.Sum256([]byte(string(claims["name"].(string))))
  1126. var hashChannel_ = make(chan []byte, 1)
  1127. hashChannel_ <- _sha256[:]
  1128. token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
  1129. _BA := strings.Split(token, ";")
  1130. BA := _BA[len(_BA)-2]
  1131. url := OvirtURL + "/ovirt-engine/api/vms/" + vmuuid + "/stop"
  1132. method := "POST"
  1133. __json := "{\"async\":\"true\"}"
  1134. sha256 := sha256.Sum256([]byte(vmuuid))
  1135. var hashChannel = make(chan []byte, 1)
  1136. hashChannel <- sha256[:]
  1137. ___json := encrypt(<-hashChannel, __json)
  1138. startVM := addVMTask{
  1139. URL: url,
  1140. JSON: ___json,
  1141. Method: method,
  1142. Headers: nil,
  1143. }
  1144. startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Version", Value: "4"})
  1145. startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Accept", Value: "application/json"})
  1146. startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Content-Type", Value: "application/json"})
  1147. startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Authorization", Value: BA})
  1148. //req.Header.Add("Version", "4")
  1149. //req.Header.Add("Accept", "application/json")
  1150. //req.Header.Add("Authorization", BA)
  1151. //req.Header.Add("Content-Type", "application/json")
  1152. //
  1153. //res, err := client.Do(req)
  1154. //defer res.Body.Close()
  1155. uuid, _ := uuidgen("APIGW-Ovirt")
  1156. __startVM, _ := json.MarshalIndent(startVM, "", " ")
  1157. //fmt.Println("StartVMHeaders: ", string(__startVMHeaders))
  1158. addTask(uuid, string(__startVM), "", "APIGW", "VM Start", vmuuid, "1", "1")
  1159. resp := _response{
  1160. Origin: "ovirt-PowerOffVM",
  1161. Message: "Done",
  1162. Code: 1000,
  1163. }
  1164. //b, _ := json.MarshalIndent(resp, "", " ")
  1165. //return c.String(http.StatusOK, string(b))
  1166. return c.JSON(http.StatusOK, resp)
  1167. }
  1168. func (o ovirt) ResetVM(c echo.Context) error {
  1169. resp := _response{
  1170. Origin: "ovirt-ResetVM",
  1171. Message: "not implemented",
  1172. Code: 1003,
  1173. }
  1174. //b, _ := json.MarshalIndent(resp, "", " ")
  1175. return c.JSON(http.StatusOK, resp)
  1176. //return c.String(http.StatusOK, string(b))
  1177. }
  1178. func (o ovirt) AddNIC(c echo.Context) error {
  1179. resp := _response{
  1180. Origin: "ovirt-AddNIC",
  1181. Message: "Done",
  1182. Code: 1000,
  1183. }
  1184. //b, _ := json.MarshalIndent(resp, "", " ")
  1185. //return c.String(http.StatusOK, string(b))
  1186. return c.JSON(http.StatusOK, resp)
  1187. }
  1188. func (o ovirt) AddDisk(c echo.Context) error {
  1189. resp := _response{
  1190. Origin: "ovirt-AddDisk",
  1191. Message: "Done",
  1192. Code: 1000,
  1193. }
  1194. //b, _ := json.MarshalIndent(resp, "", " ")
  1195. //return c.String(http.StatusOK, string(b))
  1196. return c.JSON(http.StatusOK, resp)
  1197. }
  1198. func (o ovirt) EditVM(c echo.Context) error {
  1199. resp := _response{
  1200. Origin: "ovirt-EditVM",
  1201. Message: "Done",
  1202. Code: 1000,
  1203. }
  1204. //b, _ := json.MarshalIndent(resp, "", " ")
  1205. //return c.String(http.StatusOK, string(b))
  1206. return c.JSON(http.StatusOK, resp)
  1207. }
  1208. func (o ovirt) ResetPassword(c echo.Context) error {
  1209. resp := _response{
  1210. Origin: "ovirt-ResetPassword",
  1211. Message: "not implemented",
  1212. Code: 1003,
  1213. }
  1214. //b, _ := json.MarshalIndent(resp, "", " ")
  1215. //return c.String(http.StatusOK, string(b))
  1216. return c.JSON(http.StatusOK, resp)
  1217. }
  1218. func createVM(invoice_uuid string, apiJson string, uuid string) {
  1219. type AddVMResponse struct {
  1220. NextRunConfigurationExists string `json:"next_run_configuration_exists"`
  1221. NumaTuneMode string `json:"numa_tune_mode"`
  1222. Status string `json:"status"`
  1223. StopTime int64 `json:"stop_time"`
  1224. OriginalTemplate struct {
  1225. Href string `json:"href"`
  1226. ID string `json:"id"`
  1227. } `json:"original_template"`
  1228. Template struct {
  1229. Href string `json:"href"`
  1230. ID string `json:"id"`
  1231. } `json:"template"`
  1232. Actions struct {
  1233. Link []struct {
  1234. Href string `json:"href"`
  1235. Rel string `json:"rel"`
  1236. } `json:"link"`
  1237. } `json:"actions"`
  1238. Name string `json:"name"`
  1239. Description string `json:"description"`
  1240. Comment string `json:"comment"`
  1241. Href string `json:"href"`
  1242. ID string `json:"id"`
  1243. Bios struct {
  1244. BootMenu struct {
  1245. Enabled string `json:"enabled"`
  1246. } `json:"boot_menu"`
  1247. Type string `json:"type"`
  1248. } `json:"bios"`
  1249. Console struct {
  1250. Enabled string `json:"enabled"`
  1251. } `json:"console"`
  1252. CPU struct {
  1253. Architecture string `json:"architecture"`
  1254. Topology struct {
  1255. Cores string `json:"cores"`
  1256. Sockets string `json:"sockets"`
  1257. Threads string `json:"threads"`
  1258. } `json:"topology"`
  1259. } `json:"cpu"`
  1260. Display struct {
  1261. AllowOverride string `json:"allow_override"`
  1262. CopyPasteEnabled string `json:"copy_paste_enabled"`
  1263. DisconnectAction string `json:"disconnect_action"`
  1264. FileTransferEnabled string `json:"file_transfer_enabled"`
  1265. Monitors string `json:"monitors"`
  1266. SingleQxlPci string `json:"single_qxl_pci"`
  1267. SmartcardEnabled string `json:"smartcard_enabled"`
  1268. Type string `json:"type"`
  1269. } `json:"display"`
  1270. Initialization struct {
  1271. AuthorizedSSHKeys string `json:"authorized_ssh_keys"`
  1272. CloudInitNetworkProtocol string `json:"cloud_init_network_protocol"`
  1273. CustomScript string `json:"custom_script"`
  1274. HostName string `json:"host_name"`
  1275. NicConfigurations struct {
  1276. } `json:"nic_configurations"`
  1277. RegenerateSSHKeys string `json:"regenerate_ssh_keys"`
  1278. UserName string `json:"user_name"`
  1279. } `json:"initialization"`
  1280. Io struct {
  1281. Threads string `json:"threads"`
  1282. } `json:"io"`
  1283. Memory string `json:"memory"`
  1284. Migration struct {
  1285. AutoConverge string `json:"auto_converge"`
  1286. Compressed string `json:"compressed"`
  1287. Encrypted string `json:"encrypted"`
  1288. } `json:"migration"`
  1289. Origin string `json:"origin"`
  1290. Os struct {
  1291. Boot struct {
  1292. Devices struct {
  1293. Device []string `json:"device"`
  1294. } `json:"devices"`
  1295. } `json:"boot"`
  1296. Type string `json:"type"`
  1297. } `json:"os"`
  1298. Sso struct {
  1299. Methods struct {
  1300. Method []struct {
  1301. ID string `json:"id"`
  1302. } `json:"method"`
  1303. } `json:"methods"`
  1304. } `json:"sso"`
  1305. Stateless string `json:"stateless"`
  1306. Type string `json:"type"`
  1307. Usb struct {
  1308. Enabled string `json:"enabled"`
  1309. } `json:"usb"`
  1310. Cluster struct {
  1311. Href string `json:"href"`
  1312. ID string `json:"id"`
  1313. } `json:"cluster"`
  1314. Quota struct {
  1315. ID string `json:"id"`
  1316. } `json:"quota"`
  1317. CreationStatus string `json:"creation_status"`
  1318. Link []struct {
  1319. Href string `json:"href"`
  1320. Rel string `json:"rel"`
  1321. } `json:"link"`
  1322. CPUShares string `json:"cpu_shares"`
  1323. CreationTime int64 `json:"creation_time"`
  1324. DeleteProtected string `json:"delete_protected"`
  1325. HighAvailability struct {
  1326. Enabled string `json:"enabled"`
  1327. Priority string `json:"priority"`
  1328. } `json:"high_availability"`
  1329. LargeIcon struct {
  1330. Href string `json:"href"`
  1331. ID string `json:"id"`
  1332. } `json:"large_icon"`
  1333. MemoryPolicy struct {
  1334. Ballooning string `json:"ballooning"`
  1335. Guaranteed string `json:"guaranteed"`
  1336. Max string `json:"max"`
  1337. } `json:"memory_policy"`
  1338. MigrationDowntime string `json:"migration_downtime"`
  1339. MultiQueuesEnabled string `json:"multi_queues_enabled"`
  1340. RngDevice struct {
  1341. Source string `json:"source"`
  1342. } `json:"rng_device"`
  1343. SmallIcon struct {
  1344. Href string `json:"href"`
  1345. ID string `json:"id"`
  1346. } `json:"small_icon"`
  1347. SoundcardEnabled string `json:"soundcard_enabled"`
  1348. StartPaused string `json:"start_paused"`
  1349. StorageErrorResumeBehaviour string `json:"storage_error_resume_behaviour"`
  1350. TimeZone struct {
  1351. Name string `json:"name"`
  1352. } `json:"time_zone"`
  1353. VirtioScsi struct {
  1354. Enabled string `json:"enabled"`
  1355. } `json:"virtio_scsi"`
  1356. CPUProfile struct {
  1357. Href string `json:"href"`
  1358. ID string `json:"id"`
  1359. } `json:"cpu_profile"`
  1360. }
  1361. _createVM := AddVMRequest{}
  1362. //fmt.Println(apiJson)
  1363. _err := json.Unmarshal([]byte(apiJson), &_createVM)
  1364. if _err != nil {
  1365. fmt.Println("Error in VMCreation step 1: ", _err.Error())
  1366. }
  1367. addvmresponse := AddVMResponse{}
  1368. var body []byte
  1369. {
  1370. url := _createVM.URL
  1371. method := _createVM.Method
  1372. __json := _createVM.JSON
  1373. client := &http.Client{}
  1374. _json, _ := json.Marshal(__json)
  1375. payload := strings.NewReader(string(_json))
  1376. //payload := __json
  1377. req, err := http.NewRequest(method, url, payload)
  1378. if err != nil {
  1379. fmt.Println("Error in VMCreation step 2: ", err.Error())
  1380. }
  1381. _headers := _createVM.Headers
  1382. for _, v := range _headers {
  1383. req.Header.Add(v.Name, v.Value)
  1384. }
  1385. if err != nil {
  1386. fmt.Println("Error in VMCreation step 3: ", err.Error())
  1387. }
  1388. res, err := client.Do(req)
  1389. defer res.Body.Close()
  1390. body, _ = ioutil.ReadAll(res.Body)
  1391. }
  1392. //body := runAPICall(_createVM)
  1393. err := json.Unmarshal(body, &addvmresponse)
  1394. if err != nil {
  1395. fmt.Println("Error in VMCreation step 4: ", err.Error())
  1396. }
  1397. toggleTask(uuid, 0)
  1398. // find related VMInitialization Task
  1399. //ruuid := ""
  1400. {
  1401. db, err := sql.Open("mysql", MySQLUSER+":"+MySQLPASS+"@tcp(127.0.0.1:3306)/zicloud")
  1402. if err != nil {
  1403. fmt.Println("Error in VMCreation step 3: ", _err.Error())
  1404. }
  1405. //defer db.Close()
  1406. //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")
  1407. //type Task struct {
  1408. // UUID string `json:"uuid"`
  1409. // TaskAPICall string `json:"taskapicall"`
  1410. // Ruuid string `json:"ruuid"`
  1411. // CronExpression string `json:"cronexpression"`
  1412. // Type string `json:"type"`
  1413. //}
  1414. //for results.Next() {
  1415. // var res Task
  1416. // err = results.Scan(&res.UUID, &res.TaskAPICall, &res.CronExpression, &res.Ruuid, &res.Type)
  1417. // ruuid = res.UUID
  1418. // break
  1419. //}
  1420. //update UUID and status
  1421. update2, err := db.Query("update service_profile set uuid='" + addvmresponse.ID + "' , active=1 where related_invoice='" + invoice_uuid + "'")
  1422. update, err := db.Query("update scheduler set related_uuid='" + addvmresponse.ID + "' , active=1 where related_uuid='" + invoice_uuid + "' and type=1")
  1423. defer update.Close()
  1424. defer update2.Close()
  1425. //toggleTask(ruuid, 1)
  1426. }
  1427. }
  1428. func VMInitialization(relatedUuid string, apiCall string, uuid string) {
  1429. iaas := &ovirt{}
  1430. //fmt.Println("VM :", relatedUuid)
  1431. status := iaas.vmStatus(relatedUuid)
  1432. fmt.Println("VM :", relatedUuid, " is now: ", status)
  1433. if status == "down" {
  1434. //fmt.Println("APICall: ", apiCall)
  1435. startVM := addVMTask{}
  1436. //b, _ := json.Marshal(apiCall)
  1437. _err := json.Unmarshal([]byte(apiCall), &startVM)
  1438. if _err != nil {
  1439. fmt.Println("Error in VMInitialization: ", _err.Error())
  1440. }
  1441. //fmt.Println("calling initialization for VM :", relatedUuid)
  1442. words := strings.Split(startVM.URL, "/")
  1443. //fmt.Println("Invoice : ", words[6])
  1444. _sha256 := sha256.Sum256([]byte(words[6]))
  1445. var hashChannel_ = make(chan []byte, 1)
  1446. hashChannel_ <- _sha256[:]
  1447. //fmt.Println(" startVM.JSON: ", startVM.JSON)
  1448. startVM.JSON = decrypt(<-hashChannel_, startVM.JSON)
  1449. //fmt.Println("decrypted json: ",startVM.JSON)
  1450. startVM.URL = OvirtURL + "/ovirt-engine/api/vms/" + relatedUuid + "/start"
  1451. //fmt.Println("Start URL: ", startVM.URL)
  1452. //fmt.Println("Initialize JSON: ", decrypt(<-hashChannel_, startVM.JSON))
  1453. runAPICall(startVM)
  1454. toggleTask(uuid, 0)
  1455. }
  1456. }
  1457. func vmStatistics(BA string, VMUUID string) (string, float64, float64, error) {
  1458. //ram,cpu,storage
  1459. var _disk []string
  1460. {
  1461. type DiskAttachments struct {
  1462. DiskAttachment []struct {
  1463. Active string `json:"active"`
  1464. Bootable string `json:"bootable"`
  1465. Interface string `json:"interface"`
  1466. LogicalName string `json:"logical_name"`
  1467. PassDiscard string `json:"pass_discard"`
  1468. ReadOnly string `json:"read_only"`
  1469. UsesScsiReservation string `json:"uses_scsi_reservation"`
  1470. Disk struct {
  1471. Href string `json:"href"`
  1472. ID string `json:"id"`
  1473. } `json:"disk"`
  1474. VM struct {
  1475. Href string `json:"href"`
  1476. ID string `json:"id"`
  1477. } `json:"vm"`
  1478. Href string `json:"href"`
  1479. ID string `json:"id"`
  1480. } `json:"disk_attachment"`
  1481. }
  1482. url := OvirtURL + "/ovirt-engine/api/vms/" + VMUUID + "/diskattachments"
  1483. //fmt.Println("Url:" ,url)
  1484. method := "GET"
  1485. client := &http.Client{}
  1486. req, err := http.NewRequest(method, url, nil)
  1487. if err != nil {
  1488. return "", -1, -1, errors.New("unexpected Error")
  1489. }
  1490. req.Header.Add("Version", "4")
  1491. req.Header.Add("Accept", "application/json")
  1492. req.Header.Add("Authorization", BA)
  1493. res, err := client.Do(req)
  1494. defer res.Body.Close()
  1495. body, err := ioutil.ReadAll(res.Body)
  1496. diskattachments := DiskAttachments{}
  1497. _err := json.Unmarshal(body, &diskattachments)
  1498. if _err != nil {
  1499. fmt.Println("Error in vmStatistics 1: ", _err)
  1500. }
  1501. for _, v := range diskattachments.DiskAttachment {
  1502. url := OvirtURL + "/ovirt-engine/api/disks/" + v.Disk.ID
  1503. type DiskAttachment struct {
  1504. ActualSize string `json:"actual_size"`
  1505. Alias string `json:"alias"`
  1506. Backup string `json:"backup"`
  1507. ContentType string `json:"content_type"`
  1508. Format string `json:"format"`
  1509. ImageID string `json:"image_id"`
  1510. PropagateErrors string `json:"propagate_errors"`
  1511. ProvisionedSize string `json:"provisioned_size"`
  1512. QcowVersion string `json:"qcow_version"`
  1513. Shareable string `json:"shareable"`
  1514. Sparse string `json:"sparse"`
  1515. Status string `json:"status"`
  1516. StorageType string `json:"storage_type"`
  1517. TotalSize string `json:"total_size"`
  1518. WipeAfterDelete string `json:"wipe_after_delete"`
  1519. DiskProfile struct {
  1520. Href string `json:"href"`
  1521. ID string `json:"id"`
  1522. } `json:"disk_profile"`
  1523. Quota struct {
  1524. Href string `json:"href"`
  1525. ID string `json:"id"`
  1526. } `json:"quota"`
  1527. StorageDomains struct {
  1528. StorageDomain []struct {
  1529. Href string `json:"href"`
  1530. ID string `json:"id"`
  1531. } `json:"storage_domain"`
  1532. } `json:"storage_domains"`
  1533. Actions struct {
  1534. Link []struct {
  1535. Href string `json:"href"`
  1536. Rel string `json:"rel"`
  1537. } `json:"link"`
  1538. } `json:"actions"`
  1539. Name string `json:"name"`
  1540. Description string `json:"description"`
  1541. Href string `json:"href"`
  1542. ID string `json:"id"`
  1543. Link []struct {
  1544. Href string `json:"href"`
  1545. Rel string `json:"rel"`
  1546. } `json:"link"`
  1547. }
  1548. //fmt.Println("Url:" ,url)
  1549. method := "GET"
  1550. client := &http.Client{}
  1551. req, _ := http.NewRequest(method, url, nil)
  1552. //if err != nil {
  1553. // return "Null"
  1554. //}
  1555. req.Header.Add("Version", "4")
  1556. req.Header.Add("Accept", "application/json")
  1557. req.Header.Add("Authorization", BA)
  1558. res, _ := client.Do(req)
  1559. defer res.Body.Close()
  1560. body, _ := ioutil.ReadAll(res.Body)
  1561. //fmt.Println("full response: ",string(body))
  1562. disk := DiskAttachment{}
  1563. _err := json.Unmarshal(body, &disk)
  1564. if _err != nil {
  1565. fmt.Println("Error in vmStatistics 2 : ", _err)
  1566. }
  1567. _disk = append(_disk, disk.ProvisionedSize)
  1568. //_disk = D_disk + "" + disk.ProvisionedSize+" "
  1569. }
  1570. }
  1571. url := OvirtURL + "/ovirt-engine/api/vms/" + VMUUID + "/statistics"
  1572. //fmt.Println("Url:" ,url)
  1573. method := "GET"
  1574. client := &http.Client{}
  1575. req, err := http.NewRequest(method, url, nil)
  1576. if err != nil {
  1577. return "", -1, -1, errors.New("unexpected Error")
  1578. }
  1579. req.Header.Add("Version", "4")
  1580. req.Header.Add("Accept", "application/json")
  1581. req.Header.Add("Authorization", BA)
  1582. res, err := client.Do(req)
  1583. defer res.Body.Close()
  1584. body, err := ioutil.ReadAll(res.Body)
  1585. fmt.Println("Code: ", res.StatusCode)
  1586. if err != nil || res.StatusCode == 404 {
  1587. return "", -1, -1, errors.New("unexpected Error")
  1588. }
  1589. //fmt.Println("full response: ", string(body))
  1590. _vmstatistics := VMStatistics{}
  1591. _err := json.Unmarshal(body, &_vmstatistics)
  1592. if _err != nil {
  1593. fmt.Println("Error in vmStatistics 3: ", _err)
  1594. }
  1595. cpuUUID := _vmstatistics.Statistic[4].ID
  1596. memUsedUUID := _vmstatistics.Statistic[1].ID
  1597. memTotalUUID := _vmstatistics.Statistic[0].ID
  1598. //fmt.Println(memUsedUUID)
  1599. var cpu, memUsed, memTotal string
  1600. type ItemUsage struct {
  1601. Kind string `json:"kind"`
  1602. Type string `json:"type"`
  1603. Unit string `json:"unit"`
  1604. Values struct {
  1605. Value []struct {
  1606. Datum float64 `json:"datum"`
  1607. } `json:"value"`
  1608. } `json:"values"`
  1609. VM struct {
  1610. Href string `json:"href"`
  1611. ID string `json:"id"`
  1612. } `json:"vm"`
  1613. Name string `json:"name"`
  1614. Description string `json:"description"`
  1615. Href string `json:"href"`
  1616. ID string `json:"id"`
  1617. }
  1618. {
  1619. url := OvirtURL + "/ovirt-engine/api/vms/" + VMUUID + "/statistics/" + cpuUUID
  1620. //fmt.Println("Url:" ,url)
  1621. method := "GET"
  1622. client := &http.Client{}
  1623. req, err := http.NewRequest(method, url, nil)
  1624. if err != nil {
  1625. return "", -1, -1, errors.New("unexpected Error")
  1626. }
  1627. req.Header.Add("Version", "4")
  1628. req.Header.Add("Accept", "application/json")
  1629. req.Header.Add("Authorization", BA)
  1630. res, err := client.Do(req)
  1631. defer res.Body.Close()
  1632. body, err := ioutil.ReadAll(res.Body)
  1633. cpuUsage := ItemUsage{}
  1634. _err := json.Unmarshal(body, &cpuUsage)
  1635. if _err != nil {
  1636. fmt.Println("Error in vmStatistics 4 ", _err)
  1637. }
  1638. cpu = fmt.Sprintf("%f", cpuUsage.Values.Value[0].Datum)
  1639. }
  1640. {
  1641. url := OvirtURL + "/ovirt-engine/api/vms/" + VMUUID + "/statistics/" + memUsedUUID
  1642. //fmt.Println("Url:" ,url)
  1643. method := "GET"
  1644. client := &http.Client{}
  1645. req, err := http.NewRequest(method, url, nil)
  1646. if err != nil {
  1647. return "", -1, -1, errors.New("unexpected Error")
  1648. }
  1649. req.Header.Add("Version", "4")
  1650. req.Header.Add("Accept", "application/json")
  1651. req.Header.Add("Authorization", BA)
  1652. res, err := client.Do(req)
  1653. defer res.Body.Close()
  1654. body, err := ioutil.ReadAll(res.Body)
  1655. memUsage := ItemUsage{}
  1656. _err := json.Unmarshal(body, &memUsage)
  1657. if _err != nil {
  1658. fmt.Println("Error in vmStatistics 5: ", _err)
  1659. }
  1660. memUsed = fmt.Sprintf("%f", memUsage.Values.Value[0].Datum)
  1661. }
  1662. {
  1663. url := OvirtURL + "/ovirt-engine/api/vms/" + VMUUID + "/statistics/" + memTotalUUID
  1664. //fmt.Println("Url:" ,url)
  1665. method := "GET"
  1666. client := &http.Client{}
  1667. req, err := http.NewRequest(method, url, nil)
  1668. if err != nil {
  1669. return "", -1, -1, errors.New("unexpected Error")
  1670. }
  1671. req.Header.Add("Version", "4")
  1672. req.Header.Add("Accept", "application/json")
  1673. req.Header.Add("Authorization", BA)
  1674. res, err := client.Do(req)
  1675. defer res.Body.Close()
  1676. body, err := ioutil.ReadAll(res.Body)
  1677. memUsage := ItemUsage{}
  1678. _err := json.Unmarshal(body, &memUsage)
  1679. if _err != nil {
  1680. fmt.Println("Error in vmStatistics 6: ", _err)
  1681. }
  1682. memTotal = fmt.Sprintf("%f", memUsage.Values.Value[0].Datum)
  1683. }
  1684. //fmt.Println("CPU:" ,cpu)
  1685. //fmt.Println("MEM:", memUsed)
  1686. //fmt.Println("MEM:", memTotal)
  1687. _memusage, _ := strconv.ParseFloat(memUsed, 32)
  1688. _memtotal, _ := strconv.ParseFloat(memTotal, 32)
  1689. mem := _memusage / _memtotal
  1690. _cpu, _ := strconv.ParseFloat(cpu, 64)
  1691. return strings.Join(_disk, ", "), _cpu, mem, nil
  1692. }
  1693. func (o ovirt) vmDetails(c echo.Context) error {
  1694. //name,...,traffic,ip,status
  1695. user := c.Get("user").(*jwt.Token)
  1696. claims := user.Claims.(jwt.MapClaims)
  1697. _sha256 := sha256.Sum256([]byte(string(claims["name"].(string))))
  1698. var hashChannel_ = make(chan []byte, 1)
  1699. hashChannel_ <- _sha256[:]
  1700. token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
  1701. _BA := strings.Split(token, ";")
  1702. BA := _BA[len(_BA)-2]
  1703. uuid := c.FormValue("uuid")
  1704. if len(uuid) < 5 {
  1705. resp := _response{
  1706. Origin: "vmDetails",
  1707. Message: "Missing UUID",
  1708. Code: 1001,
  1709. }
  1710. return c.JSON(http.StatusNotFound, resp)
  1711. }
  1712. type vmStatus struct {
  1713. NextRunConfigurationExists string `json:"next_run_configuration_exists"`
  1714. NumaTuneMode string `json:"numa_tune_mode"`
  1715. Status string `json:"status"`
  1716. StopTime int64 `json:"stop_time"`
  1717. OriginalTemplate struct {
  1718. Href string `json:"href"`
  1719. ID string `json:"id"`
  1720. } `json:"original_template"`
  1721. Template struct {
  1722. Href string `json:"href"`
  1723. ID string `json:"id"`
  1724. } `json:"template"`
  1725. Actions struct {
  1726. Link []struct {
  1727. Href string `json:"href"`
  1728. Rel string `json:"rel"`
  1729. } `json:"link"`
  1730. } `json:"actions"`
  1731. Name string `json:"name"`
  1732. Description string `json:"description"`
  1733. Comment string `json:"comment"`
  1734. Href string `json:"href"`
  1735. ID string `json:"id"`
  1736. Bios struct {
  1737. BootMenu struct {
  1738. Enabled string `json:"enabled"`
  1739. } `json:"boot_menu"`
  1740. Type string `json:"type"`
  1741. } `json:"bios"`
  1742. CPU struct {
  1743. Architecture string `json:"architecture"`
  1744. Topology struct {
  1745. Cores string `json:"cores"`
  1746. Sockets string `json:"sockets"`
  1747. Threads string `json:"threads"`
  1748. } `json:"topology"`
  1749. } `json:"cpu"`
  1750. Display struct {
  1751. AllowOverride string `json:"allow_override"`
  1752. CopyPasteEnabled string `json:"copy_paste_enabled"`
  1753. DisconnectAction string `json:"disconnect_action"`
  1754. FileTransferEnabled string `json:"file_transfer_enabled"`
  1755. Monitors string `json:"monitors"`
  1756. SingleQxlPci string `json:"single_qxl_pci"`
  1757. SmartcardEnabled string `json:"smartcard_enabled"`
  1758. Type string `json:"type"`
  1759. } `json:"display"`
  1760. Initialization struct {
  1761. AuthorizedSSHKeys string `json:"authorized_ssh_keys"`
  1762. CloudInitNetworkProtocol string `json:"cloud_init_network_protocol"`
  1763. CustomScript string `json:"custom_script"`
  1764. HostName string `json:"host_name"`
  1765. NicConfigurations struct {
  1766. } `json:"nic_configurations"`
  1767. RegenerateSSHKeys string `json:"regenerate_ssh_keys"`
  1768. UserName string `json:"user_name"`
  1769. } `json:"initialization"`
  1770. Io struct {
  1771. Threads string `json:"threads"`
  1772. } `json:"io"`
  1773. Memory string `json:"memory"`
  1774. Migration struct {
  1775. AutoConverge string `json:"auto_converge"`
  1776. Compressed string `json:"compressed"`
  1777. Encrypted string `json:"encrypted"`
  1778. } `json:"migration"`
  1779. Origin string `json:"origin"`
  1780. Os struct {
  1781. Boot struct {
  1782. Devices struct {
  1783. Device []string `json:"device"`
  1784. } `json:"devices"`
  1785. } `json:"boot"`
  1786. Type string `json:"type"`
  1787. } `json:"os"`
  1788. Sso struct {
  1789. Methods struct {
  1790. Method []struct {
  1791. ID string `json:"id"`
  1792. } `json:"method"`
  1793. } `json:"methods"`
  1794. } `json:"sso"`
  1795. Stateless string `json:"stateless"`
  1796. Type string `json:"type"`
  1797. Usb struct {
  1798. Enabled string `json:"enabled"`
  1799. } `json:"usb"`
  1800. Cluster struct {
  1801. Href string `json:"href"`
  1802. ID string `json:"id"`
  1803. } `json:"cluster"`
  1804. Quota struct {
  1805. ID string `json:"id"`
  1806. } `json:"quota"`
  1807. Link []struct {
  1808. Href string `json:"href"`
  1809. Rel string `json:"rel"`
  1810. } `json:"link"`
  1811. CPUShares string `json:"cpu_shares"`
  1812. CreationTime int64 `json:"creation_time"`
  1813. DeleteProtected string `json:"delete_protected"`
  1814. HighAvailability struct {
  1815. Enabled string `json:"enabled"`
  1816. Priority string `json:"priority"`
  1817. } `json:"high_availability"`
  1818. LargeIcon struct {
  1819. Href string `json:"href"`
  1820. ID string `json:"id"`
  1821. } `json:"large_icon"`
  1822. MemoryPolicy struct {
  1823. Ballooning string `json:"ballooning"`
  1824. Guaranteed string `json:"guaranteed"`
  1825. Max string `json:"max"`
  1826. } `json:"memory_policy"`
  1827. MigrationDowntime string `json:"migration_downtime"`
  1828. MultiQueuesEnabled string `json:"multi_queues_enabled"`
  1829. PlacementPolicy struct {
  1830. Affinity string `json:"affinity"`
  1831. Hosts struct {
  1832. Host []struct {
  1833. Href string `json:"href"`
  1834. ID string `json:"id"`
  1835. } `json:"host"`
  1836. } `json:"hosts"`
  1837. } `json:"placement_policy"`
  1838. SmallIcon struct {
  1839. Href string `json:"href"`
  1840. ID string `json:"id"`
  1841. } `json:"small_icon"`
  1842. StartPaused string `json:"start_paused"`
  1843. StorageErrorResumeBehaviour string `json:"storage_error_resume_behaviour"`
  1844. TimeZone struct {
  1845. Name string `json:"name"`
  1846. } `json:"time_zone"`
  1847. CPUProfile struct {
  1848. Href string `json:"href"`
  1849. ID string `json:"id"`
  1850. } `json:"cpu_profile"`
  1851. }
  1852. //url := "https://ovirt-cl.zi-tel.com/ovirt-engine/api/vms/c1a44128-6c6c-406b-99d8-4a68a99380c9"
  1853. url := OvirtURL + "/ovirt-engine/api/vms/" + uuid
  1854. //fmt.Println("Url:" ,url)
  1855. method := "GET"
  1856. client := &http.Client{}
  1857. req, _ := http.NewRequest(method, url, nil)
  1858. //if err != nil {
  1859. // return "Null"
  1860. //}
  1861. req.Header.Add("Version", "4")
  1862. req.Header.Add("Accept", "application/json")
  1863. req.Header.Add("Authorization", BA)
  1864. res, _ := client.Do(req)
  1865. defer res.Body.Close()
  1866. body, _ := ioutil.ReadAll(res.Body)
  1867. //fmt.Println("full response: ",string(body))
  1868. _vmstatus := vmStatus{}
  1869. _err := json.Unmarshal(body, &_vmstatus)
  1870. if _err != nil {
  1871. resp := _response{
  1872. Origin: "vmDetails",
  1873. Message: "Not Found",
  1874. Code: 1001,
  1875. }
  1876. return c.JSON(http.StatusNotFound, resp)
  1877. }
  1878. disk, cpu, ram, err := vmStatistics(BA, uuid)
  1879. if err != nil {
  1880. fmt.Println("Error in vmDetails 2 : ", err)
  1881. resp := _response{
  1882. Origin: "vmDetails",
  1883. Message: "Unexpected Error",
  1884. Code: 1001,
  1885. }
  1886. return c.JSON(http.StatusInternalServerError, resp)
  1887. }
  1888. type AutoGenerated struct {
  1889. Message struct {
  1890. Disk string `json:"Disk"`
  1891. Memory string `json:"Memory"`
  1892. CPU string `json:"CPU"`
  1893. NetAddress string `json:"NetAddress"`
  1894. Traffic string `json:"Traffic"`
  1895. Status string `json:"Status"`
  1896. Name string `json:"Name"`
  1897. } `json:"message"`
  1898. Origin string `json:"origin"`
  1899. Code int `json:"code"`
  1900. }
  1901. resp := AutoGenerated{
  1902. Message: struct {
  1903. Disk string `json:"Disk"`
  1904. Memory string `json:"Memory"`
  1905. CPU string `json:"CPU"`
  1906. NetAddress string `json:"NetAddress"`
  1907. Traffic string `json:"Traffic"`
  1908. Status string `json:"Status"`
  1909. Name string `json:"Name"`
  1910. }{
  1911. Disk: disk,
  1912. Memory: fmt.Sprintf("%f", ram),
  1913. CPU: fmt.Sprintf("%f", cpu),
  1914. NetAddress: "",
  1915. Traffic: "",
  1916. Status: _vmstatus.Status,
  1917. Name: _vmstatus.Name,
  1918. },
  1919. Origin: "vmDetails",
  1920. Code: 1000,
  1921. }
  1922. return c.JSON(http.StatusOK, resp)
  1923. //return _vmstatus.Status, _vmstatus.Name, disk, cpu, ram
  1924. }
  1925. func (o ovirt) ovirtPayment(c echo.Context) error {
  1926. invoiceUuid := c.FormValue("invoiceUuid")
  1927. db, err := sql.Open("mysql", MySQLUSER+":"+MySQLPASS+"@tcp(127.0.0.1:3306)/zicloud")
  1928. //results, err := db.Query("SELECT uuid as UUID ,task_apiCall as TaskAPICall , cron_expression as CronExpression , related_uuid as Ruuid, type FROM scheduler where active=1")
  1929. ///TODO: check duplicate payment confirmation by Invoice table
  1930. if err != nil {
  1931. }
  1932. update, err := db.Query("update scheduler set active='1' where related_uuid='" + invoiceUuid + "' and type=0")
  1933. defer db.Close()
  1934. if err != nil {
  1935. }
  1936. defer update.Close()
  1937. resp := _response{
  1938. Origin: "ovirt-ovirtPayment",
  1939. Message: "Done",
  1940. Code: 1000,
  1941. }
  1942. //b, _ := json.MarshalIndent(resp, "", " ")
  1943. //return c.String(http.StatusOK, string(b))
  1944. return c.JSON(http.StatusOK, resp)
  1945. }
  1946. func listNIC(VMUUID string, BA string) []struct {
  1947. Mac string `json:"mac"`
  1948. IPv4 string `json:"IPv4"`
  1949. IPv6 string `json:"IPv6"`
  1950. ReportedDevices struct {
  1951. Mac string `json:"mac"`
  1952. IPv4 string `json:"IPv4"`
  1953. IPv6 string `json:"IPv6"`
  1954. } `json:"reported_devices"`
  1955. } {
  1956. type NICList struct {
  1957. NIC []struct {
  1958. Mac string `json:"mac"`
  1959. IPv4 string `json:"IPv4"`
  1960. IPv6 string `json:"IPv6"`
  1961. ReportedDevices struct {
  1962. Mac string `json:"mac"`
  1963. IPv4 string `json:"IPv4"`
  1964. IPv6 string `json:"IPv6"`
  1965. } `json:"reported_devices"`
  1966. } `json:"NIC"`
  1967. }
  1968. type VMNIC struct {
  1969. Nic []struct {
  1970. Interface string `json:"interface"`
  1971. Linked string `json:"linked"`
  1972. Mac struct {
  1973. Address string `json:"address"`
  1974. } `json:"mac"`
  1975. Plugged string `json:"plugged"`
  1976. ReportedDevices struct {
  1977. ReportedDevice []struct {
  1978. Ips struct {
  1979. IP []struct {
  1980. Address string `json:"address"`
  1981. Version string `json:"version"`
  1982. } `json:"ip"`
  1983. } `json:"ips"`
  1984. Mac struct {
  1985. Address string `json:"address"`
  1986. } `json:"mac"`
  1987. Type string `json:"type"`
  1988. Name string `json:"name"`
  1989. Description string `json:"description"`
  1990. Href string `json:"href"`
  1991. ID string `json:"id"`
  1992. } `json:"reported_device"`
  1993. } `json:"reported_devices"`
  1994. VnicProfile struct {
  1995. Href string `json:"href"`
  1996. ID string `json:"id"`
  1997. } `json:"vnic_profile"`
  1998. Actions struct {
  1999. Link []struct {
  2000. Href string `json:"href"`
  2001. Rel string `json:"rel"`
  2002. } `json:"link"`
  2003. } `json:"actions"`
  2004. Name string `json:"name"`
  2005. Href string `json:"href"`
  2006. ID string `json:"id"`
  2007. VM struct {
  2008. Href string `json:"href"`
  2009. ID string `json:"id"`
  2010. } `json:"vm"`
  2011. Link []struct {
  2012. Href string `json:"href"`
  2013. Rel string `json:"rel"`
  2014. } `json:"link"`
  2015. } `json:"nic"`
  2016. }
  2017. url := "https://ovirt-cl.zi-tel.com/ovirt-engine/api/vms/" + VMUUID + "/nics"
  2018. method := "GET"
  2019. payload := strings.NewReader(``)
  2020. client := &http.Client{
  2021. }
  2022. req, err := http.NewRequest(method, url, payload)
  2023. if err != nil {
  2024. //fmt.Println(err)
  2025. return nil
  2026. }
  2027. req.Header.Add("Version", "4")
  2028. req.Header.Add("Accept", "application/json")
  2029. req.Header.Add("Authorization", BA)
  2030. res, err := client.Do(req)
  2031. if err != nil {
  2032. //fmt.Println(err)
  2033. ///TODO: ErrorHandling
  2034. return nil
  2035. }
  2036. defer res.Body.Close()
  2037. body, err := ioutil.ReadAll(res.Body)
  2038. if err != nil {
  2039. //fmt.Println(err)
  2040. ///TODO: ErrorHandling
  2041. return nil
  2042. }
  2043. _VMNIC := VMNIC{}
  2044. err = json.Unmarshal(body, &_VMNIC)
  2045. //fmt.Println("ListNIC: res", string(body))
  2046. if err != nil {
  2047. ///TODO: ErrorHandling
  2048. //fmt.Println(err)
  2049. //return CPUPrice, memPrice, StoragePrice, IPPrice, extraBWPrice
  2050. }
  2051. _NICList := NICList{}
  2052. _Data := _NICList.NIC
  2053. x := struct {
  2054. Mac string `json:"mac"`
  2055. IPv4 string `json:"IPv4"`
  2056. IPv6 string `json:"IPv6"`
  2057. ReportedDevices struct {
  2058. Mac string `json:"mac"`
  2059. IPv4 string `json:"IPv4"`
  2060. IPv6 string `json:"IPv6"`
  2061. } `json:"reported_devices"`
  2062. }{}
  2063. for _, i := range _VMNIC.Nic {
  2064. x.IPv4 = "1.1.1.1"
  2065. ///TODO:GetAssignedIP
  2066. x.IPv6 = "Null"
  2067. x.Mac = i.Mac.Address
  2068. x.ReportedDevices.Mac = i.ReportedDevices.ReportedDevice[0].Mac.Address
  2069. x.ReportedDevices.IPv4 = i.ReportedDevices.ReportedDevice[0].Ips.IP[0].Address
  2070. x.ReportedDevices.IPv6 = i.ReportedDevices.ReportedDevice[0].Ips.IP[1].Address
  2071. _Data = append(_Data, x)
  2072. }
  2073. _NICList.NIC = _Data
  2074. return _NICList.NIC
  2075. }
  2076. func listDisks(VMUUID string, ba string) []struct {
  2077. Name string `json:"Name"`
  2078. TotalSize string `json:"TotalSize"`
  2079. ActualSize string `json:"ActualSize"`
  2080. } {
  2081. type DiskList struct {
  2082. Disk []struct {
  2083. Name string `json:"Name"`
  2084. TotalSize string `json:"TotalSize"`
  2085. ActualSize string `json:"ActualSize"`
  2086. } `json:"Disk"`
  2087. }
  2088. type ListDisks struct {
  2089. DiskAttachment []struct {
  2090. Active string `json:"active"`
  2091. Bootable string `json:"bootable"`
  2092. Interface string `json:"interface"`
  2093. LogicalName string `json:"logical_name"`
  2094. PassDiscard string `json:"pass_discard"`
  2095. ReadOnly string `json:"read_only"`
  2096. UsesScsiReservation string `json:"uses_scsi_reservation"`
  2097. Disk struct {
  2098. Href string `json:"href"`
  2099. ID string `json:"id"`
  2100. } `json:"disk"`
  2101. VM struct {
  2102. Href string `json:"href"`
  2103. ID string `json:"id"`
  2104. } `json:"vm"`
  2105. Href string `json:"href"`
  2106. ID string `json:"id"`
  2107. } `json:"disk_attachment"`
  2108. }
  2109. url := "https://ovirt-cl.zi-tel.com/ovirt-engine/api/vms/" + VMUUID + "/diskattachments"
  2110. method := "GET"
  2111. payload := strings.NewReader(``)
  2112. client := &http.Client{
  2113. }
  2114. req, err := http.NewRequest(method, url, payload)
  2115. if err != nil {
  2116. //fmt.Println(err)
  2117. return nil
  2118. }
  2119. req.Header.Add("Version", "4")
  2120. req.Header.Add("Accept", "application/json")
  2121. req.Header.Add("Authorization", ba)
  2122. res, err := client.Do(req)
  2123. if err != nil {
  2124. //fmt.Println(err)
  2125. return nil
  2126. }
  2127. defer res.Body.Close()
  2128. body, err := ioutil.ReadAll(res.Body)
  2129. //fmt.Println("ListDisk: res", string(body))
  2130. if err != nil {
  2131. //fmt.Println(err)
  2132. return nil
  2133. }
  2134. _ListDisks := ListDisks{}
  2135. err = json.Unmarshal(body, &_ListDisks)
  2136. if err != nil {
  2137. //fmt.Println(err)
  2138. return nil
  2139. }
  2140. _DiskList := DiskList{}
  2141. for _, v := range _ListDisks.DiskAttachment {
  2142. _DiskList.Disk = append(_DiskList.Disk, DiskDetails(v.Disk.ID, ba))
  2143. }
  2144. return _DiskList.Disk
  2145. }
  2146. func DiskDetails(id string, ba string) struct {
  2147. Name string `json:"Name"`
  2148. TotalSize string `json:"TotalSize"`
  2149. ActualSize string `json:"ActualSize"`
  2150. } {
  2151. type DiskDetail struct {
  2152. ActualSize string `json:"actual_size"`
  2153. Alias string `json:"alias"`
  2154. Backup string `json:"backup"`
  2155. ContentType string `json:"content_type"`
  2156. Format string `json:"format"`
  2157. ImageID string `json:"image_id"`
  2158. PropagateErrors string `json:"propagate_errors"`
  2159. ProvisionedSize string `json:"provisioned_size"`
  2160. QcowVersion string `json:"qcow_version"`
  2161. Shareable string `json:"shareable"`
  2162. Sparse string `json:"sparse"`
  2163. Status string `json:"status"`
  2164. StorageType string `json:"storage_type"`
  2165. TotalSize string `json:"total_size"`
  2166. WipeAfterDelete string `json:"wipe_after_delete"`
  2167. DiskProfile struct {
  2168. Href string `json:"href"`
  2169. ID string `json:"id"`
  2170. } `json:"disk_profile"`
  2171. Quota struct {
  2172. Href string `json:"href"`
  2173. ID string `json:"id"`
  2174. } `json:"quota"`
  2175. StorageDomains struct {
  2176. StorageDomain []struct {
  2177. Href string `json:"href"`
  2178. ID string `json:"id"`
  2179. } `json:"storage_domain"`
  2180. } `json:"storage_domains"`
  2181. Actions struct {
  2182. Link []struct {
  2183. Href string `json:"href"`
  2184. Rel string `json:"rel"`
  2185. } `json:"link"`
  2186. } `json:"actions"`
  2187. Name string `json:"name"`
  2188. Description string `json:"description"`
  2189. Href string `json:"href"`
  2190. ID string `json:"id"`
  2191. Link []struct {
  2192. Href string `json:"href"`
  2193. Rel string `json:"rel"`
  2194. } `json:"link"`
  2195. }
  2196. //fmt.Println("List Disk: ",id)
  2197. url := "https://ovirt-cl.zi-tel.com/ovirt-engine/api/disks/" + id
  2198. method := "GET"
  2199. payload := strings.NewReader(``)
  2200. client := &http.Client{
  2201. }
  2202. req, err := http.NewRequest(method, url, payload)
  2203. if err != nil {
  2204. //fmt.Println(err)
  2205. }
  2206. req.Header.Add("Version", "4")
  2207. req.Header.Add("Accept", "application/json")
  2208. req.Header.Add("Authorization", ba)
  2209. res, err := client.Do(req)
  2210. if err != nil {
  2211. //fmt.Println(err)
  2212. }
  2213. defer res.Body.Close()
  2214. body, err := ioutil.ReadAll(res.Body)
  2215. if err != nil {
  2216. //fmt.Println(err)
  2217. }
  2218. _DiskDetail := DiskDetail{}
  2219. err = json.Unmarshal(body, &_DiskDetail)
  2220. if err != nil {
  2221. //fmt.Println(err)
  2222. }
  2223. Disk := struct {
  2224. Name string `json:"Name"`
  2225. TotalSize string `json:"TotalSize"`
  2226. ActualSize string `json:"ActualSize"`
  2227. }{
  2228. Name: _DiskDetail.Alias,
  2229. TotalSize: _DiskDetail.TotalSize,
  2230. ActualSize: _DiskDetail.ActualSize,
  2231. }
  2232. return Disk
  2233. }
  2234. func (o ovirt) listTemplate(c echo.Context) error {
  2235. type templateList struct {
  2236. Template []struct {
  2237. Status string `json:"status"`
  2238. Version struct {
  2239. VersionName string `json:"version_name"`
  2240. VersionNumber string `json:"version_number"`
  2241. BaseTemplate struct {
  2242. Href string `json:"href"`
  2243. ID string `json:"id"`
  2244. } `json:"base_template"`
  2245. } `json:"version"`
  2246. Actions struct {
  2247. Link []struct {
  2248. Href string `json:"href"`
  2249. Rel string `json:"rel"`
  2250. } `json:"link"`
  2251. } `json:"actions"`
  2252. Name string `json:"name"`
  2253. Description string `json:"description"`
  2254. Comment string `json:"comment"`
  2255. Href string `json:"href"`
  2256. ID string `json:"id"`
  2257. Bios struct {
  2258. BootMenu struct {
  2259. Enabled string `json:"enabled"`
  2260. } `json:"boot_menu"`
  2261. Type string `json:"type"`
  2262. } `json:"bios"`
  2263. CPU struct {
  2264. Architecture string `json:"architecture"`
  2265. Topology struct {
  2266. Cores string `json:"cores"`
  2267. Sockets string `json:"sockets"`
  2268. Threads string `json:"threads"`
  2269. } `json:"topology"`
  2270. } `json:"cpu"`
  2271. Display struct {
  2272. AllowOverride string `json:"allow_override"`
  2273. CopyPasteEnabled string `json:"copy_paste_enabled"`
  2274. DisconnectAction string `json:"disconnect_action"`
  2275. FileTransferEnabled string `json:"file_transfer_enabled"`
  2276. Monitors string `json:"monitors"`
  2277. SingleQxlPci string `json:"single_qxl_pci"`
  2278. SmartcardEnabled string `json:"smartcard_enabled"`
  2279. Type string `json:"type"`
  2280. } `json:"display"`
  2281. Io struct {
  2282. Threads string `json:"threads"`
  2283. } `json:"io"`
  2284. Memory string `json:"memory"`
  2285. Migration struct {
  2286. AutoConverge string `json:"auto_converge"`
  2287. Compressed string `json:"compressed"`
  2288. Encrypted string `json:"encrypted"`
  2289. } `json:"migration"`
  2290. Origin string `json:"origin"`
  2291. Os struct {
  2292. Boot struct {
  2293. Devices struct {
  2294. Device []string `json:"device"`
  2295. } `json:"devices"`
  2296. } `json:"boot"`
  2297. Type string `json:"type"`
  2298. } `json:"os"`
  2299. Sso struct {
  2300. Methods struct {
  2301. Method []struct {
  2302. ID string `json:"id"`
  2303. } `json:"method"`
  2304. } `json:"methods"`
  2305. } `json:"sso"`
  2306. Stateless string `json:"stateless"`
  2307. Type string `json:"type"`
  2308. Usb struct {
  2309. Enabled string `json:"enabled"`
  2310. } `json:"usb"`
  2311. Link []struct {
  2312. Href string `json:"href"`
  2313. Rel string `json:"rel"`
  2314. } `json:"link"`
  2315. CPUShares string `json:"cpu_shares"`
  2316. CreationTime int64 `json:"creation_time"`
  2317. DeleteProtected string `json:"delete_protected"`
  2318. HighAvailability struct {
  2319. Enabled string `json:"enabled"`
  2320. Priority string `json:"priority"`
  2321. } `json:"high_availability"`
  2322. LargeIcon struct {
  2323. Href string `json:"href"`
  2324. ID string `json:"id"`
  2325. } `json:"large_icon"`
  2326. MemoryPolicy struct {
  2327. Guaranteed string `json:"guaranteed"`
  2328. Max string `json:"max"`
  2329. } `json:"memory_policy"`
  2330. MigrationDowntime string `json:"migration_downtime"`
  2331. MultiQueuesEnabled string `json:"multi_queues_enabled"`
  2332. PlacementPolicy struct {
  2333. Affinity string `json:"affinity"`
  2334. } `json:"placement_policy"`
  2335. SmallIcon struct {
  2336. Href string `json:"href"`
  2337. ID string `json:"id"`
  2338. } `json:"small_icon"`
  2339. StartPaused string `json:"start_paused"`
  2340. StorageErrorResumeBehaviour string `json:"storage_error_resume_behaviour"`
  2341. Cluster struct {
  2342. Href string `json:"href"`
  2343. ID string `json:"id"`
  2344. } `json:"cluster,omitempty"`
  2345. TimeZone struct {
  2346. Name string `json:"name"`
  2347. } `json:"time_zone,omitempty"`
  2348. CPUProfile struct {
  2349. Href string `json:"href"`
  2350. ID string `json:"id"`
  2351. } `json:"cpu_profile,omitempty"`
  2352. Initialization struct {
  2353. AuthorizedSSHKeys string `json:"authorized_ssh_keys"`
  2354. CloudInitNetworkProtocol string `json:"cloud_init_network_protocol"`
  2355. CustomScript string `json:"custom_script"`
  2356. HostName string `json:"host_name"`
  2357. NicConfigurations struct {
  2358. } `json:"nic_configurations"`
  2359. RegenerateSSHKeys string `json:"regenerate_ssh_keys"`
  2360. UserName string `json:"user_name"`
  2361. } `json:"initialization,omitempty"`
  2362. } `json:"template"`
  2363. }
  2364. type templateListResponse struct {
  2365. Data []struct {
  2366. Name string `json:"name"`
  2367. } `json:"Data"`
  2368. Message string `json:"message"`
  2369. Origin string `json:"origin"`
  2370. Code int `json:"code"`
  2371. }
  2372. user := c.Get("user").(*jwt.Token)
  2373. claims := user.Claims.(jwt.MapClaims)
  2374. _sha256 := sha256.Sum256([]byte(string(claims["name"].(string))))
  2375. var hashChannel_ = make(chan []byte, 1)
  2376. hashChannel_ <- _sha256[:]
  2377. token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
  2378. _BA := strings.Split(token, ";")
  2379. BA := _BA[len(_BA)-2]
  2380. url := OvirtURL + "/ovirt-engine/api/templates?filter=true&search=Cloud"
  2381. client := &http.Client{}
  2382. req, err := http.NewRequest("GET", url, nil)
  2383. if err != nil {
  2384. fmt.Println(err)
  2385. }
  2386. req.Header.Add("Version", "4")
  2387. req.Header.Add("Accept", "application/json")
  2388. req.Header.Add("Authorization", BA)
  2389. res, err := client.Do(req)
  2390. defer res.Body.Close()
  2391. body, err := ioutil.ReadAll(res.Body)
  2392. _templateList := templateList{}
  2393. err = json.Unmarshal(body, &_templateList)
  2394. //fmt.Println("resp:",string(body))
  2395. _templateListResponse := templateListResponse{
  2396. Data: nil,
  2397. Message: "Done",
  2398. Origin: "ListTemplate",
  2399. Code: 1000,
  2400. }
  2401. _Data := _templateListResponse.Data
  2402. y := struct {
  2403. Name string `json:"name"`
  2404. }{}
  2405. for _, v := range _templateList.Template {
  2406. y.Name = v.Name
  2407. _Data = append(_Data, y)
  2408. }
  2409. _templateListResponse.Data = _Data
  2410. return c.JSON(http.StatusOK, _templateListResponse)
  2411. //return c.String(http.StatusOK, string(b))
  2412. }
  2413. func (o ovirt) vmHistory(c echo.Context) error {
  2414. type VMStatistics struct {
  2415. Statistic []struct {
  2416. Kind string `json:"kind"`
  2417. Type string `json:"type"`
  2418. Unit string `json:"unit"`
  2419. Values struct {
  2420. Value []struct {
  2421. Datum int64 `json:"datum"`
  2422. } `json:"value"`
  2423. } `json:"values"`
  2424. VM struct {
  2425. Href string `json:"href"`
  2426. ID string `json:"id"`
  2427. } `json:"vm,omitempty"`
  2428. Name string `json:"name"`
  2429. Description string `json:"description"`
  2430. Href string `json:"href,omitempty"`
  2431. ID string `json:"id"`
  2432. } `json:"statistic"`
  2433. }
  2434. type VMStatisticsResponse struct {
  2435. Data []struct {
  2436. Kind string `json:"kind"`
  2437. Type string `json:"type"`
  2438. Unit string `json:"unit"`
  2439. Values struct {
  2440. Value []struct {
  2441. Datum int64 `json:"datum"`
  2442. } `json:"value"`
  2443. } `json:"values"`
  2444. Name string `json:"name"`
  2445. Description string `json:"description"`
  2446. //Href string `json:"href,omitempty"`
  2447. //ID string `json:"id"`
  2448. } `json:"statistic"`
  2449. Message string `json:"message"`
  2450. Origin string `json:"origin"`
  2451. Code int `json:"code"`
  2452. }
  2453. user := c.Get("user").(*jwt.Token)
  2454. claims := user.Claims.(jwt.MapClaims)
  2455. _sha256 := sha256.Sum256([]byte(string(claims["name"].(string))))
  2456. var hashChannel_ = make(chan []byte, 1)
  2457. hashChannel_ <- _sha256[:]
  2458. token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
  2459. _BA := strings.Split(token, ";")
  2460. BA := _BA[len(_BA)-2]
  2461. vmuuid := c.FormValue("VmUUID")
  2462. url := OvirtURL + "/ovirt-engine/api/vms/" + vmuuid + "/statistics"
  2463. client := &http.Client{}
  2464. req, err := http.NewRequest("GET", url, nil)
  2465. if err != nil {
  2466. fmt.Println(err)
  2467. }
  2468. req.Header.Add("Version", "4")
  2469. req.Header.Add("Accept", "application/json")
  2470. req.Header.Add("Authorization", BA)
  2471. res, err := client.Do(req)
  2472. defer res.Body.Close()
  2473. body, err := ioutil.ReadAll(res.Body)
  2474. _VMStatistics := VMStatistics{}
  2475. err = json.Unmarshal(body, &_VMStatistics)
  2476. _VMStatisticsResponse := VMStatisticsResponse{
  2477. Data: nil,
  2478. Message: "Done",
  2479. Origin: "vmHistory",
  2480. Code: 1000,
  2481. }
  2482. _Data := _VMStatisticsResponse.Data
  2483. y := struct {
  2484. Kind string `json:"kind"`
  2485. Type string `json:"type"`
  2486. Unit string `json:"unit"`
  2487. Values struct {
  2488. Value []struct {
  2489. Datum int64 `json:"datum"`
  2490. } `json:"value"`
  2491. } `json:"values"`
  2492. Name string `json:"name"`
  2493. Description string `json:"description"`
  2494. //Href string `json:"href,omitempty"`
  2495. //ID string `json:"id"`
  2496. }{}
  2497. for _, v := range _VMStatistics.Statistic {
  2498. y.Kind = v.Kind
  2499. y.Unit = v.Unit
  2500. y.Type = v.Type
  2501. y.Values = v.Values
  2502. y.Name = v.Name
  2503. y.Description = v.Description
  2504. _Data = append(_Data, y)
  2505. }
  2506. _VMStatisticsResponse.Data = _Data
  2507. return c.JSON(http.StatusOK, _VMStatisticsResponse)
  2508. }
  2509. func (o ovirt) SSHKeyGen(c echo.Context) error {
  2510. type SSHKeyGenResponse struct {
  2511. Message string `json:"message"`
  2512. Origin string `json:"origin"`
  2513. Code int `json:"code"`
  2514. }
  2515. user := c.Get("user").(*jwt.Token)
  2516. claims := user.Claims.(jwt.MapClaims)
  2517. email:=fmt.Sprintf("%s",claims["mail"])
  2518. fmt.Println(email)
  2519. mrand.Seed(time.Now().Unix())
  2520. var output strings.Builder
  2521. //Only lowercase
  2522. charSet := "abcdedfghijklmnopqrstABCDEFGHIJKLMNOP0123456789"
  2523. length := 20
  2524. for i := 0; i < length; i++ {
  2525. random := mrand.Intn(len(charSet))
  2526. randomChar := charSet[random]
  2527. output.WriteString(string(randomChar))
  2528. }
  2529. publicKeyBlock := &pem.Block{}
  2530. {
  2531. // generate key
  2532. privatekey, err := rsa.GenerateKey(rand.Reader, 1024)
  2533. if err != nil {
  2534. fmt.Printf("Cannot generate RSA key\n")
  2535. //os.Exit(1)
  2536. }
  2537. publickey := &privatekey.PublicKey
  2538. // dump private key to file
  2539. var privateKeyBytes []byte = x509.MarshalPKCS1PrivateKey(privatekey)
  2540. privateKeyBlock := &pem.Block{
  2541. Type: "RSA PRIVATE KEY",
  2542. Bytes: privateKeyBytes,
  2543. }
  2544. privatePem, err := os.Create("/tmp/" + output.String() + "-private.pem")
  2545. if err != nil {
  2546. fmt.Printf("error when create private.pem: %s \n", err)
  2547. //os.Exit(1)
  2548. }
  2549. err = pem.Encode(privatePem, privateKeyBlock)
  2550. if err != nil {
  2551. fmt.Printf("error when encode private pem: %s \n", err)
  2552. //os.Exit(1)
  2553. }
  2554. // dump public key to file
  2555. publicKeyBytes, err := x509.MarshalPKIXPublicKey(publickey)
  2556. if err != nil {
  2557. fmt.Printf("error when dumping publickey: %s \n", err)
  2558. //os.Exit(1)
  2559. }
  2560. publicKeyBlock = &pem.Block{
  2561. Type: "PUBLIC KEY",
  2562. Bytes: publicKeyBytes,
  2563. }
  2564. publicPem, err := os.Create("/tmp/" + output.String() + "-public.pem")
  2565. if err != nil {
  2566. fmt.Printf("error when create public.pem: %s \n", err)
  2567. //os.Exit(1)
  2568. }
  2569. err = pem.Encode(publicPem, publicKeyBlock)
  2570. if err != nil {
  2571. fmt.Printf("error when encode public pem: %s \n", err)
  2572. //os.Exit(1)
  2573. }
  2574. sendMail("Generated SSH Key pairs is attached to this email", "ZiCloud KeyPair", "inbox@sassan.co", []string{"/tmp/" + output.String() + "-public.pem", "/tmp/" + output.String() + "-private.pem"})
  2575. }
  2576. _SSHKeyGenResponse := SSHKeyGenResponse{
  2577. Message: string(pem.EncodeToMemory(publicKeyBlock)),
  2578. Origin: "SSHKeyGen",
  2579. Code: 1000,
  2580. }
  2581. return c.JSON(http.StatusOK, _SSHKeyGenResponse)
  2582. }