ovirt.go 68 KB

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