ovirt.go 88 KB

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