ovirt.go 100 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471
  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. type VMDescr struct {
  1236. VMName string `json:"vmname"`
  1237. VMCpu string `json:"vmCpu"`
  1238. VMMem string `json:"vmMem"`
  1239. VMNIC string `json:"vmnic"`
  1240. VMBW string `json:"vmbw"`
  1241. VMUUID string `json:"vmuuid"`
  1242. Invoice string `json:"invoice"`
  1243. }
  1244. type EditVMPayment struct {
  1245. Data struct {
  1246. Price struct {
  1247. CPU float64 `json:"cpu"`
  1248. Mem float64 `json:"mem"`
  1249. Disk float64 `json:"disk"`
  1250. Nic float64 `json:"nic"`
  1251. BW float64 `json:"bw"`
  1252. SUM float64 `json:"sum"`
  1253. SUMRaw float64 `json:"SUMRaw"`
  1254. Period string `json:"period"`
  1255. } `json:"price"`
  1256. InvoiceUUID string `json:"invoiceUUID"`
  1257. } `json:"data"`
  1258. Message string `json:"message"`
  1259. Origin string `json:"origin"`
  1260. Code int `json:"code"`
  1261. }
  1262. user := c.Get("user").(*jwt.Token)
  1263. claims := user.Claims.(jwt.MapClaims)
  1264. _sha256 := sha256.Sum256([]byte(string(claims["name"].(string))))
  1265. var hashChannel_ = make(chan []byte, 1)
  1266. hashChannel_ <- _sha256[:]
  1267. token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
  1268. _BA := strings.Split(token, ";")
  1269. BA := _BA[len(_BA)-2]
  1270. var vmname, vmuuid, vmdescr, vmcomment, templatename, cpuSock, cpuCore, cpuThread, mem, Disk, nic, period, extraBW string
  1271. coupon := 0
  1272. vmname = login(BA).AuthenticatedUser.ID + "-_-" + c.FormValue("VmName")
  1273. vmdescr = c.FormValue("VmDescr")
  1274. vmcomment = c.FormValue("VmComment")
  1275. templatename = c.FormValue("VmTempl")
  1276. cpuThread = c.FormValue("VmCPU")
  1277. Disk = c.FormValue("VmDisk")
  1278. period = c.FormValue("VmPeriod")
  1279. nic = c.FormValue("VmNIC")
  1280. extraBW = c.FormValue("extraBW")
  1281. vmuuid = c.FormValue("VMUUID")
  1282. // sshKey := c.FormValue("sshKey")
  1283. // rootpass := c.FormValue("rootpass")
  1284. coupon, _ = strconv.Atoi(c.FormValue("coupon"))
  1285. cpuCore = "1"
  1286. cpuSock = "1"
  1287. mem = c.FormValue("VmMem")
  1288. url := OvirtURL + "/ovirt-engine/api/vms"
  1289. method := "POST"
  1290. //addvmresponse := AddVMResponse{}O
  1291. editvm := AddVMRequest{
  1292. URL: url,
  1293. JSON: struct {
  1294. Name string `json:"name"`
  1295. Description string `json:"description"`
  1296. Comment string `json:"comment"`
  1297. Cluster struct {
  1298. Name string `json:"name"`
  1299. } `json:"cluster"`
  1300. Template struct {
  1301. Name string `json:"name"`
  1302. } `json:"template"`
  1303. CPU struct {
  1304. Topology struct {
  1305. Sockets string `json:"sockets"`
  1306. Cores string `json:"cores"`
  1307. Threads string `json:"threads"`
  1308. } `json:"topology"`
  1309. } `json:"cpu"`
  1310. Memory string `json:"memory"`
  1311. MemoryPolicy struct {
  1312. Ballooning string `json:"ballooning"`
  1313. Guaranteed string `json:"guaranteed"`
  1314. OverCommit struct {
  1315. Percent string `json:"percent"`
  1316. } `json:"over_commit"`
  1317. } `json:"memory_policy"`
  1318. }{
  1319. Name: vmname,
  1320. Description: vmdescr,
  1321. Comment: vmcomment,
  1322. Cluster: struct {
  1323. Name string `json:"name"`
  1324. }{Name: "Default"},
  1325. Template: struct {
  1326. Name string `json:"name"`
  1327. }{Name: templatename},
  1328. CPU: struct {
  1329. Topology struct {
  1330. Sockets string `json:"sockets"`
  1331. Cores string `json:"cores"`
  1332. Threads string `json:"threads"`
  1333. } `json:"topology"`
  1334. }{
  1335. struct {
  1336. Sockets string `json:"sockets"`
  1337. Cores string `json:"cores"`
  1338. Threads string `json:"threads"`
  1339. }{
  1340. Sockets: cpuSock,
  1341. Cores: cpuCore,
  1342. Threads: cpuThread,
  1343. },
  1344. },
  1345. Memory: mem,
  1346. MemoryPolicy: struct {
  1347. Ballooning string `json:"ballooning"`
  1348. Guaranteed string `json:"guaranteed"`
  1349. OverCommit struct {
  1350. Percent string `json:"percent"`
  1351. } `json:"over_commit"`
  1352. }{
  1353. Ballooning: "true",
  1354. Guaranteed: mem,
  1355. OverCommit: struct {
  1356. Percent string `json:"percent"`
  1357. }{Percent: "10"},
  1358. },
  1359. },
  1360. Method: method,
  1361. Headers: nil,
  1362. }
  1363. editvm.Headers = append(editvm.Headers, struct {
  1364. Name string `json:"Name"`
  1365. Value string `json:"Value"`
  1366. }{
  1367. Name: "Accept",
  1368. Value: "application/json",
  1369. })
  1370. editvm.Headers = append(editvm.Headers, struct {
  1371. Name string `json:"Name"`
  1372. Value string `json:"Value"`
  1373. }{
  1374. Name: "Authorization",
  1375. Value: BA,
  1376. })
  1377. editvm.Headers = append(editvm.Headers, struct {
  1378. Name string `json:"Name"`
  1379. Value string `json:"Value"`
  1380. }{
  1381. Name: "Content-Type",
  1382. Value: "application/json",
  1383. })
  1384. // uuid, _ := uuidgen("APIGW-Ovirt-addVMTask")
  1385. //invoiceUUID, _ := uuidgen("APIGW-FakeInvoice")
  1386. CPUPrice, memPrice, StoragePrice, IPPrice, extraBWPrice, SUM, SUMRaw, invoiceUUID := IaaSEdit(login(BA).AuthenticatedUser.ID, period, cpuThread, mem, Disk, nic, extraBW, false, coupon, vmuuid)
  1387. type JSONDetails struct {
  1388. Name string `json:"name"`
  1389. Value string `json:"value"`
  1390. Type string `json:"type"`
  1391. }
  1392. /*_jsonDetail := [8]JSONDetails{}
  1393. {
  1394. _jsonDetail[0].Name = "Period"
  1395. _jsonDetail[0].Value = period
  1396. _jsonDetail[0].Type = "int"
  1397. _jsonDetail[1].Name = "cpuThread"
  1398. _jsonDetail[1].Value = cpuThread
  1399. _jsonDetail[1].Type = "int"
  1400. _jsonDetail[2].Name = "mem"
  1401. _jsonDetail[2].Value = mem
  1402. _jsonDetail[2].Type = "int"
  1403. _jsonDetail[3].Name = "Disk"
  1404. _jsonDetail[3].Value = Disk
  1405. _jsonDetail[3].Type = "int"
  1406. _jsonDetail[4].Name = "nic"
  1407. _jsonDetail[4].Value = nic
  1408. _jsonDetail[4].Type = "int"
  1409. _jsonDetail[5].Name = "extraBW"
  1410. _jsonDetail[5].Value = extraBW
  1411. _jsonDetail[5].Type = "int"
  1412. _jsonDetail[6].Name = "coupon"
  1413. _jsonDetail[6].Value = fmt.Sprintf("%d", coupon)
  1414. _jsonDetail[6].Type = "int"
  1415. _jsonDetail[7].Name = "Template"
  1416. _jsonDetail[7].Value = templatename
  1417. _jsonDetail[7].Type = "string"
  1418. }
  1419. jsonDetail, _ := json.Marshal(_jsonDetail)
  1420. */
  1421. responseInvoiece := EditVMPayment{
  1422. Data: struct {
  1423. Price struct {
  1424. CPU float64 `json:"cpu"`
  1425. Mem float64 `json:"mem"`
  1426. Disk float64 `json:"disk"`
  1427. Nic float64 `json:"nic"`
  1428. BW float64 `json:"bw"`
  1429. SUM float64 `json:"sum"`
  1430. SUMRaw float64 `json:"SUMRaw"`
  1431. Period string `json:"period"`
  1432. } `json:"price"`
  1433. InvoiceUUID string `json:"invoiceUUID"`
  1434. }{
  1435. Price: struct {
  1436. CPU float64 `json:"cpu"`
  1437. Mem float64 `json:"mem"`
  1438. Disk float64 `json:"disk"`
  1439. Nic float64 `json:"nic"`
  1440. BW float64 `json:"bw"`
  1441. SUM float64 `json:"sum"`
  1442. SUMRaw float64 `json:"SUMRaw"`
  1443. Period string `json:"period"`
  1444. }{
  1445. CPU: CPUPrice,
  1446. Mem: memPrice,
  1447. Disk: StoragePrice,
  1448. Nic: IPPrice,
  1449. BW: extraBWPrice,
  1450. SUM: SUM,
  1451. SUMRaw: SUMRaw,
  1452. Period: period,
  1453. },
  1454. InvoiceUUID: invoiceUUID,
  1455. },
  1456. Message: "Done",
  1457. Origin: "EditVM",
  1458. Code: 1000,
  1459. }
  1460. responseInvoiece_fake := EditVMPayment{
  1461. Data: struct {
  1462. Price struct {
  1463. CPU float64 `json:"cpu"`
  1464. Mem float64 `json:"mem"`
  1465. Disk float64 `json:"disk"`
  1466. Nic float64 `json:"nic"`
  1467. BW float64 `json:"bw"`
  1468. SUM float64 `json:"sum"`
  1469. SUMRaw float64 `json:"SUMRaw"`
  1470. Period string `json:"period"`
  1471. } `json:"price"`
  1472. InvoiceUUID string `json:"invoiceUUID"`
  1473. }{
  1474. Price: struct {
  1475. CPU float64 `json:"cpu"`
  1476. Mem float64 `json:"mem"`
  1477. Disk float64 `json:"disk"`
  1478. Nic float64 `json:"nic"`
  1479. BW float64 `json:"bw"`
  1480. SUM float64 `json:"sum"`
  1481. SUMRaw float64 `json:"SUMRaw"`
  1482. Period string `json:"period"`
  1483. }{
  1484. CPU: 100,
  1485. Mem: 100,
  1486. Disk: 100,
  1487. Nic: 100,
  1488. BW: 100,
  1489. SUM: 100,
  1490. SUMRaw: 100,
  1491. Period: "12",
  1492. },
  1493. InvoiceUUID: "556a5032-09de-4430-b1e1-48a2ef84d62f",
  1494. },
  1495. Message: "Done",
  1496. Origin: "EditVM",
  1497. Code: 1000,
  1498. }
  1499. // if len(invoiceUUID) < 5 {
  1500. // resp := _response{
  1501. // Origin: "ovirt-editvm",
  1502. // Message: "Error on Invoice Calculation",
  1503. // Code: 1001,
  1504. // }
  1505. // b, _ := json.MarshalIndent(resp, "", " ")
  1506. // return c.String(http.StatusBadRequest, string(b))
  1507. // }
  1508. fmt.Println("EditVM: ", editvm)
  1509. fmt.Print(responseInvoiece)
  1510. return c.JSON(http.StatusOK, responseInvoiece_fake)
  1511. // return c.JSON(http.StatusOK, fakeResponse)
  1512. // __createVM, _ := json.MarshalIndent(editvm, "", " ")
  1513. // Add VM Task
  1514. // addTask(uuid, string(__createVM), "", "APIGW", "VM Creation for "+claims["name"].(string), invoiceUUID, "0", "0")
  1515. /*
  1516. {
  1517. db, err := sql.Open("mysql", MySQLUSER+":"+MySQLPASS+"@tcp(127.0.0.1:3306)/zicloud")
  1518. if err != nil {
  1519. resp := _response{
  1520. Origin: "ovirt-Editvm",
  1521. Message: "Error on connecting db for save add vm result",
  1522. Code: 1001,
  1523. }
  1524. b, _ := json.MarshalIndent(resp, "", " ")
  1525. return c.String(http.StatusBadRequest, string(b))
  1526. }
  1527. defer db.Close()
  1528. insert, err := db.Query("INSERT INTO service_profile VALUES ( '" + invoiceUUID + "'," +
  1529. "'" + claims["IPAUid"].(string) + "'," +
  1530. "'" + "VM" + "'," +
  1531. "'" + "" + "'," +
  1532. "'" + login(BA).AuthenticatedUser.ID + "'," +
  1533. "NOW()" + "," +
  1534. "NOW() ," +
  1535. "-1" + "," +
  1536. "'" + vmname + "'," +
  1537. "'" + string(jsonDetail) + "'," +
  1538. "'" + invoiceUUID + "' )")
  1539. defer insert.Close()
  1540. if err != nil {
  1541. fmt.Println("Error in EditVM: ", err.Error())
  1542. }
  1543. }
  1544. // Start Task
  1545. {
  1546. url := OvirtURL + "/ovirt-engine/api/vms/" + invoiceUUID + "/start"
  1547. method := "POST"
  1548. nicAddress := "172.20.15.251"
  1549. nicMask := "255.255.255.0"
  1550. nicGW := "172.20.15.1"
  1551. __json := fmt.Sprintf(`
  1552. {
  1553. "async":"true",
  1554. "use_cloud_init": "true",
  1555. "vm": {
  1556. "initialization": {
  1557. "authorized_ssh_keys": "%s",
  1558. "host_name": "Sassan.local",
  1559. "user_name": "root",
  1560. "root_password": "%s",
  1561. "nic_configurations": {
  1562. "nic_configuration": [
  1563. {
  1564. "name": "eth0",
  1565. "on_boot": "true",
  1566. "boot_protocol": "static",
  1567. "ip": {
  1568. "address": "%s",
  1569. "netmask": "%s",
  1570. "gateway": "%s"
  1571. }
  1572. }
  1573. ]
  1574. },
  1575. "dns_servers": "172.20.11.11"
  1576. }
  1577. }
  1578. }
  1579. `, sshKey, rootpass, nicAddress, nicMask, nicGW)
  1580. sha256 := sha256.Sum256([]byte(invoiceUUID))
  1581. var hashChannel = make(chan []byte, 1)
  1582. hashChannel <- sha256[:]
  1583. ___json := encrypt(<-hashChannel, __json)
  1584. startVM := addVMTask{
  1585. URL: url,
  1586. JSON: ___json,
  1587. Method: method,
  1588. Headers: nil,
  1589. }
  1590. startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Version", Value: "4"})
  1591. startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Accept", Value: "application/json"})
  1592. startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Content-Type", Value: "application/json"})
  1593. startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Authorization", Value: BA})
  1594. uuid, _ := uuidgen("APIGW-Ovirt-CloudInit")
  1595. __startVM, _ := json.MarshalIndent(startVM, "", " ")
  1596. //fmt.Println("StartVMHeaders: ", string(__startVMHeaders))
  1597. addTask(uuid, string(__startVM), "", "APIGW", "VM Initialization", invoiceUUID, "1", "0")
  1598. }
  1599. //resp := _response{
  1600. // Origin: "ovirt-addvm",
  1601. // Message: resposeInvoice
  1602. // Code: 1000,
  1603. //}
  1604. return c.JSON(http.StatusOK, responseInvoiece)
  1605. */
  1606. }
  1607. //func (o ovirt) EditVM(c echo.Context) error {
  1608. // resp := _response{
  1609. // Origin: "ovirt-EditVM",
  1610. // Message: "Done",
  1611. // Code: 1000,
  1612. // }
  1613. // //b, _ := json.MarshalIndent(resp, "", " ")
  1614. // //return c.String(http.StatusOK, string(b))
  1615. // return c.JSON(http.StatusOK, resp)
  1616. //}
  1617. func (o ovirt) ResetPassword(c echo.Context) error {
  1618. resp := _response{
  1619. Origin: "ovirt-ResetPassword",
  1620. Message: "not implemented",
  1621. Code: 1003,
  1622. }
  1623. //b, _ := json.MarshalIndent(resp, "", " ")
  1624. //return c.String(http.StatusOK, string(b))
  1625. return c.JSON(http.StatusOK, resp)
  1626. }
  1627. func createVM(invoice_uuid string, apiJson string, uuid string) {
  1628. type AddVMResponse struct {
  1629. NextRunConfigurationExists string `json:"next_run_configuration_exists"`
  1630. NumaTuneMode string `json:"numa_tune_mode"`
  1631. Status string `json:"status"`
  1632. StopTime int64 `json:"stop_time"`
  1633. OriginalTemplate struct {
  1634. Href string `json:"href"`
  1635. ID string `json:"id"`
  1636. } `json:"original_template"`
  1637. Template struct {
  1638. Href string `json:"href"`
  1639. ID string `json:"id"`
  1640. } `json:"template"`
  1641. Actions struct {
  1642. Link []struct {
  1643. Href string `json:"href"`
  1644. Rel string `json:"rel"`
  1645. } `json:"link"`
  1646. } `json:"actions"`
  1647. Name string `json:"name"`
  1648. Description string `json:"description"`
  1649. Comment string `json:"comment"`
  1650. Href string `json:"href"`
  1651. ID string `json:"id"`
  1652. Bios struct {
  1653. BootMenu struct {
  1654. Enabled string `json:"enabled"`
  1655. } `json:"boot_menu"`
  1656. Type string `json:"type"`
  1657. } `json:"bios"`
  1658. Console struct {
  1659. Enabled string `json:"enabled"`
  1660. } `json:"console"`
  1661. CPU struct {
  1662. Architecture string `json:"architecture"`
  1663. Topology struct {
  1664. Cores string `json:"cores"`
  1665. Sockets string `json:"sockets"`
  1666. Threads string `json:"threads"`
  1667. } `json:"topology"`
  1668. } `json:"cpu"`
  1669. Display struct {
  1670. AllowOverride string `json:"allow_override"`
  1671. CopyPasteEnabled string `json:"copy_paste_enabled"`
  1672. DisconnectAction string `json:"disconnect_action"`
  1673. FileTransferEnabled string `json:"file_transfer_enabled"`
  1674. Monitors string `json:"monitors"`
  1675. SingleQxlPci string `json:"single_qxl_pci"`
  1676. SmartcardEnabled string `json:"smartcard_enabled"`
  1677. Type string `json:"type"`
  1678. } `json:"display"`
  1679. Initialization struct {
  1680. AuthorizedSSHKeys string `json:"authorized_ssh_keys"`
  1681. CloudInitNetworkProtocol string `json:"cloud_init_network_protocol"`
  1682. CustomScript string `json:"custom_script"`
  1683. HostName string `json:"host_name"`
  1684. NicConfigurations struct {
  1685. } `json:"nic_configurations"`
  1686. RegenerateSSHKeys string `json:"regenerate_ssh_keys"`
  1687. UserName string `json:"user_name"`
  1688. } `json:"initialization"`
  1689. Io struct {
  1690. Threads string `json:"threads"`
  1691. } `json:"io"`
  1692. Memory string `json:"memory"`
  1693. Migration struct {
  1694. AutoConverge string `json:"auto_converge"`
  1695. Compressed string `json:"compressed"`
  1696. Encrypted string `json:"encrypted"`
  1697. } `json:"migration"`
  1698. Origin string `json:"origin"`
  1699. Os struct {
  1700. Boot struct {
  1701. Devices struct {
  1702. Device []string `json:"device"`
  1703. } `json:"devices"`
  1704. } `json:"boot"`
  1705. Type string `json:"type"`
  1706. } `json:"os"`
  1707. Sso struct {
  1708. Methods struct {
  1709. Method []struct {
  1710. ID string `json:"id"`
  1711. } `json:"method"`
  1712. } `json:"methods"`
  1713. } `json:"sso"`
  1714. Stateless string `json:"stateless"`
  1715. Type string `json:"type"`
  1716. Usb struct {
  1717. Enabled string `json:"enabled"`
  1718. } `json:"usb"`
  1719. Cluster struct {
  1720. Href string `json:"href"`
  1721. ID string `json:"id"`
  1722. } `json:"cluster"`
  1723. Quota struct {
  1724. ID string `json:"id"`
  1725. } `json:"quota"`
  1726. CreationStatus string `json:"creation_status"`
  1727. Link []struct {
  1728. Href string `json:"href"`
  1729. Rel string `json:"rel"`
  1730. } `json:"link"`
  1731. CPUShares string `json:"cpu_shares"`
  1732. CreationTime int64 `json:"creation_time"`
  1733. DeleteProtected string `json:"delete_protected"`
  1734. HighAvailability struct {
  1735. Enabled string `json:"enabled"`
  1736. Priority string `json:"priority"`
  1737. } `json:"high_availability"`
  1738. LargeIcon struct {
  1739. Href string `json:"href"`
  1740. ID string `json:"id"`
  1741. } `json:"large_icon"`
  1742. MemoryPolicy struct {
  1743. Ballooning string `json:"ballooning"`
  1744. Guaranteed string `json:"guaranteed"`
  1745. Max string `json:"max"`
  1746. } `json:"memory_policy"`
  1747. MigrationDowntime string `json:"migration_downtime"`
  1748. MultiQueuesEnabled string `json:"multi_queues_enabled"`
  1749. RngDevice struct {
  1750. Source string `json:"source"`
  1751. } `json:"rng_device"`
  1752. SmallIcon struct {
  1753. Href string `json:"href"`
  1754. ID string `json:"id"`
  1755. } `json:"small_icon"`
  1756. SoundcardEnabled string `json:"soundcard_enabled"`
  1757. StartPaused string `json:"start_paused"`
  1758. StorageErrorResumeBehaviour string `json:"storage_error_resume_behaviour"`
  1759. TimeZone struct {
  1760. Name string `json:"name"`
  1761. } `json:"time_zone"`
  1762. VirtioScsi struct {
  1763. Enabled string `json:"enabled"`
  1764. } `json:"virtio_scsi"`
  1765. CPUProfile struct {
  1766. Href string `json:"href"`
  1767. ID string `json:"id"`
  1768. } `json:"cpu_profile"`
  1769. }
  1770. _createVM := AddVMRequest{}
  1771. //fmt.Println(apiJson)
  1772. _err := json.Unmarshal([]byte(apiJson), &_createVM)
  1773. if _err != nil {
  1774. fmt.Println(apiJson)
  1775. fmt.Println("Error in VMCreation step 1: ", _err.Error())
  1776. }
  1777. addvmresponse := AddVMResponse{}
  1778. var body []byte
  1779. {
  1780. url := _createVM.URL
  1781. method := _createVM.Method
  1782. __json := _createVM.JSON
  1783. client := &http.Client{}
  1784. _json, _ := json.Marshal(__json)
  1785. payload := strings.NewReader(string(_json))
  1786. //payload := __json
  1787. fmt.Println("First unmarshal", string(_json))
  1788. fmt.Println("second unmarshal", __json.Description)
  1789. req, err := http.NewRequest(method, url, payload)
  1790. if err != nil {
  1791. fmt.Println("Error in VMCreation step 2: ", err.Error())
  1792. }
  1793. _headers := _createVM.Headers
  1794. for _, v := range _headers {
  1795. req.Header.Add(v.Name, v.Value)
  1796. }
  1797. if err != nil {
  1798. fmt.Println("Error in VMCreation step 3: ", err.Error())
  1799. }
  1800. res, err := client.Do(req)
  1801. if err != nil {
  1802. fmt.Println("Error in VMCreation step 3.5: ", err.Error())
  1803. }
  1804. defer res.Body.Close()
  1805. body, _ = ioutil.ReadAll(res.Body)
  1806. }
  1807. //body := runAPICall(_createVM)
  1808. err := json.Unmarshal(body, &addvmresponse)
  1809. if err != nil {
  1810. fmt.Println("Error in VMCreation step 4: ", err.Error())
  1811. }
  1812. toggleTask(uuid, 0)
  1813. // find related VMInitialization Task
  1814. //ruuid := ""
  1815. {
  1816. db, err := sql.Open("mysql", MySQLUSER+":"+MySQLPASS+"@tcp(127.0.0.1:3306)/zicloud")
  1817. if err != nil {
  1818. fmt.Println("Error in VMCreation step 3: ", _err.Error())
  1819. }
  1820. update2, err := db.Query("update service_profile set uuid='" + addvmresponse.ID + "' , modification_date=NOW() , active=1 where related_invoice='" + invoice_uuid + "'")
  1821. update, err := db.Query("update scheduler set related_uuid='" + addvmresponse.ID + "' , active=1 where related_uuid='" + invoice_uuid + "' and type=1")
  1822. defer update.Close()
  1823. defer update2.Close()
  1824. //toggleTask(ruuid, 1)
  1825. }
  1826. }
  1827. func VMInitialization(relatedUuid string, apiCall string, uuid string) {
  1828. iaas := &ovirt{}
  1829. //fmt.Println("VM :", relatedUuid)
  1830. status := iaas.vmStatus(relatedUuid)
  1831. fmt.Println("VM :", relatedUuid, " is now: ", status)
  1832. if status == "down" || status == "suspended" {
  1833. //fmt.Println("APICall: ", apiCall)
  1834. startVM := addVMTask{}
  1835. //b, _ := json.Marshal(apiCall)
  1836. _err := json.Unmarshal([]byte(apiCall), &startVM)
  1837. if _err != nil {
  1838. fmt.Println("Error in VMInitialization: ", _err.Error())
  1839. }
  1840. //fmt.Println("calling initialization for VM :", relatedUuid)
  1841. words := strings.Split(startVM.URL, "/")
  1842. //fmt.Println("Invoice : ", words[6])
  1843. _sha256 := sha256.Sum256([]byte(words[6]))
  1844. var hashChannel_ = make(chan []byte, 1)
  1845. hashChannel_ <- _sha256[:]
  1846. //fmt.Println(" startVM.JSON: ", startVM.JSON)
  1847. startVM.JSON = decrypt(<-hashChannel_, startVM.JSON)
  1848. //fmt.Println("decrypted json: ",startVM.JSON)
  1849. startVM.URL = OvirtURL + "/ovirt-engine/api/vms/" + relatedUuid + "/start"
  1850. //fmt.Println("Start URL: ", startVM.URL)
  1851. //fmt.Println("Initialize JSON: ", decrypt(<-hashChannel_, startVM.JSON))
  1852. runAPICall(startVM)
  1853. toggleTask(uuid, 0)
  1854. }
  1855. }
  1856. func vmStatistics(BA string, VMUUID string) (string, float64, float64, error) {
  1857. //ram,cpu,storage
  1858. var _disk []string
  1859. {
  1860. type DiskAttachments struct {
  1861. DiskAttachment []struct {
  1862. Active string `json:"active"`
  1863. Bootable string `json:"bootable"`
  1864. Interface string `json:"interface"`
  1865. LogicalName string `json:"logical_name"`
  1866. PassDiscard string `json:"pass_discard"`
  1867. ReadOnly string `json:"read_only"`
  1868. UsesScsiReservation string `json:"uses_scsi_reservation"`
  1869. Disk struct {
  1870. Href string `json:"href"`
  1871. ID string `json:"id"`
  1872. } `json:"disk"`
  1873. VM struct {
  1874. Href string `json:"href"`
  1875. ID string `json:"id"`
  1876. } `json:"vm"`
  1877. Href string `json:"href"`
  1878. ID string `json:"id"`
  1879. } `json:"disk_attachment"`
  1880. }
  1881. url := OvirtURL + "/ovirt-engine/api/vms/" + VMUUID + "/diskattachments"
  1882. //fmt.Println("Url:" ,url)
  1883. method := "GET"
  1884. client := &http.Client{}
  1885. req, err := http.NewRequest(method, url, nil)
  1886. if err != nil {
  1887. return "", -1, -1, errors.New("unexpected Error")
  1888. }
  1889. req.Header.Add("Version", "4")
  1890. req.Header.Add("Accept", "application/json")
  1891. req.Header.Add("Authorization", BA)
  1892. res, err := client.Do(req)
  1893. body, err := ioutil.ReadAll(res.Body)
  1894. defer res.Body.Close()
  1895. diskattachments := DiskAttachments{
  1896. DiskAttachment: []struct {
  1897. Active string "json:\"active\""
  1898. Bootable string "json:\"bootable\""
  1899. Interface string "json:\"interface\""
  1900. LogicalName string "json:\"logical_name\""
  1901. PassDiscard string "json:\"pass_discard\""
  1902. ReadOnly string "json:\"read_only\""
  1903. UsesScsiReservation string "json:\"uses_scsi_reservation\""
  1904. Disk struct {
  1905. Href string "json:\"href\""
  1906. ID string "json:\"id\""
  1907. } "json:\"disk\""
  1908. VM struct {
  1909. Href string "json:\"href\""
  1910. ID string "json:\"id\""
  1911. } "json:\"vm\""
  1912. Href string "json:\"href\""
  1913. ID string "json:\"id\""
  1914. }{},
  1915. }
  1916. _err := json.Unmarshal(body, &diskattachments)
  1917. if _err != nil {
  1918. fmt.Println("Error in vmStatistics 1: ", _err)
  1919. fmt.Println("Error: ", string(body))
  1920. return "", -1, -1, errors.New("unexpected Error")
  1921. }
  1922. for _, v := range diskattachments.DiskAttachment {
  1923. url := OvirtURL + "/ovirt-engine/api/disks/" + v.Disk.ID
  1924. type DiskAttachment struct {
  1925. ActualSize string `json:"actual_size"`
  1926. Alias string `json:"alias"`
  1927. Backup string `json:"backup"`
  1928. ContentType string `json:"content_type"`
  1929. Format string `json:"format"`
  1930. ImageID string `json:"image_id"`
  1931. PropagateErrors string `json:"propagate_errors"`
  1932. ProvisionedSize string `json:"provisioned_size"`
  1933. QcowVersion string `json:"qcow_version"`
  1934. Shareable string `json:"shareable"`
  1935. Sparse string `json:"sparse"`
  1936. Status string `json:"status"`
  1937. StorageType string `json:"storage_type"`
  1938. TotalSize string `json:"total_size"`
  1939. WipeAfterDelete string `json:"wipe_after_delete"`
  1940. DiskProfile struct {
  1941. Href string `json:"href"`
  1942. ID string `json:"id"`
  1943. } `json:"disk_profile"`
  1944. Quota struct {
  1945. Href string `json:"href"`
  1946. ID string `json:"id"`
  1947. } `json:"quota"`
  1948. StorageDomains struct {
  1949. StorageDomain []struct {
  1950. Href string `json:"href"`
  1951. ID string `json:"id"`
  1952. } `json:"storage_domain"`
  1953. } `json:"storage_domains"`
  1954. Actions struct {
  1955. Link []struct {
  1956. Href string `json:"href"`
  1957. Rel string `json:"rel"`
  1958. } `json:"link"`
  1959. } `json:"actions"`
  1960. Name string `json:"name"`
  1961. Description string `json:"description"`
  1962. Href string `json:"href"`
  1963. ID string `json:"id"`
  1964. Link []struct {
  1965. Href string `json:"href"`
  1966. Rel string `json:"rel"`
  1967. } `json:"link"`
  1968. }
  1969. //fmt.Println("Url:" ,url)
  1970. method := "GET"
  1971. client := &http.Client{}
  1972. req, _ := http.NewRequest(method, url, nil)
  1973. //if err != nil {
  1974. // return "Null"
  1975. //}
  1976. req.Header.Add("Version", "4")
  1977. req.Header.Add("Accept", "application/json")
  1978. req.Header.Add("Authorization", BA)
  1979. res, _ := client.Do(req)
  1980. body, _ := ioutil.ReadAll(res.Body)
  1981. //fmt.Println("full response: ",string(body))
  1982. disk := DiskAttachment{}
  1983. _err := json.Unmarshal(body, &disk)
  1984. if _err != nil {
  1985. fmt.Println("Error in vmStatistics 2 : ", _err)
  1986. fmt.Println("Error: ", string(body))
  1987. }
  1988. defer res.Body.Close()
  1989. _disk = append(_disk, disk.ProvisionedSize)
  1990. //_disk = D_disk + "" + disk.ProvisionedSize+" "
  1991. }
  1992. }
  1993. url := OvirtURL + "/ovirt-engine/api/vms/" + VMUUID + "/statistics"
  1994. //fmt.Println("Url:" ,url)
  1995. method := "GET"
  1996. client := &http.Client{}
  1997. req, err := http.NewRequest(method, url, nil)
  1998. if err != nil {
  1999. return "", -1, -1, errors.New("unexpected Error")
  2000. }
  2001. req.Header.Add("Version", "4")
  2002. req.Header.Add("Accept", "application/json")
  2003. req.Header.Add("Authorization", BA)
  2004. res, err := client.Do(req)
  2005. body, err := ioutil.ReadAll(res.Body)
  2006. // fmt.Println("Code: ", res.StatusCode, " VMUUID:", VMUUID)
  2007. if err != nil || res.StatusCode == 404 {
  2008. return "", -1, -1, errors.New("unexpected Error")
  2009. }
  2010. defer res.Body.Close()
  2011. //fmt.Println("full response: ", string(body))
  2012. _vmstatistics := VMStatistics{}
  2013. _err := json.Unmarshal(body, &_vmstatistics)
  2014. if _err != nil {
  2015. fmt.Println("Error in vmStatistics 3: ", _err)
  2016. fmt.Println("Error: ", string(body))
  2017. return "", -1, -1, errors.New("unexpected Error")
  2018. }
  2019. cpuUUID := _vmstatistics.Statistic[4].ID
  2020. memUsedUUID := _vmstatistics.Statistic[1].ID
  2021. memTotalUUID := _vmstatistics.Statistic[0].ID
  2022. //fmt.Println(memUsedUUID)
  2023. var cpu, memUsed, memTotal string
  2024. type ItemUsage struct {
  2025. Kind string `json:"kind"`
  2026. Type string `json:"type"`
  2027. Unit string `json:"unit"`
  2028. Values struct {
  2029. Value []struct {
  2030. Datum float64 `json:"datum"`
  2031. } `json:"value"`
  2032. } `json:"values"`
  2033. VM struct {
  2034. Href string `json:"href"`
  2035. ID string `json:"id"`
  2036. } `json:"vm"`
  2037. Name string `json:"name"`
  2038. Description string `json:"description"`
  2039. Href string `json:"href"`
  2040. ID string `json:"id"`
  2041. }
  2042. {
  2043. url := OvirtURL + "/ovirt-engine/api/vms/" + VMUUID + "/statistics/" + cpuUUID
  2044. //fmt.Println("Url:" ,url)
  2045. method := "GET"
  2046. client := &http.Client{}
  2047. req, err := http.NewRequest(method, url, nil)
  2048. if err != nil {
  2049. return "", -1, -1, errors.New("unexpected Error")
  2050. }
  2051. req.Header.Add("Version", "4")
  2052. req.Header.Add("Accept", "application/json")
  2053. req.Header.Add("Authorization", BA)
  2054. res, err := client.Do(req)
  2055. body, err := ioutil.ReadAll(res.Body)
  2056. defer res.Body.Close()
  2057. cpuUsage := ItemUsage{}
  2058. _err := json.Unmarshal(body, &cpuUsage)
  2059. if _err != nil {
  2060. fmt.Println("Error in vmStatistics 4 ", _err)
  2061. fmt.Println("Error: ", string(body))
  2062. }
  2063. cpu = fmt.Sprintf("%f", cpuUsage.Values.Value[0].Datum)
  2064. }
  2065. {
  2066. url := OvirtURL + "/ovirt-engine/api/vms/" + VMUUID + "/statistics/" + memUsedUUID
  2067. //fmt.Println("Url:" ,url)
  2068. method := "GET"
  2069. client := &http.Client{}
  2070. req, err := http.NewRequest(method, url, nil)
  2071. if err != nil {
  2072. return "", -1, -1, errors.New("unexpected Error")
  2073. }
  2074. req.Header.Add("Version", "4")
  2075. req.Header.Add("Accept", "application/json")
  2076. req.Header.Add("Authorization", BA)
  2077. res, err := client.Do(req)
  2078. body, err := ioutil.ReadAll(res.Body)
  2079. defer res.Body.Close()
  2080. memUsage := ItemUsage{}
  2081. _err := json.Unmarshal(body, &memUsage)
  2082. if _err != nil {
  2083. fmt.Println("Error in vmStatistics 5: ", _err)
  2084. fmt.Println("Error: ", string(body))
  2085. }
  2086. memUsed = fmt.Sprintf("%f", memUsage.Values.Value[0].Datum)
  2087. }
  2088. {
  2089. url := OvirtURL + "/ovirt-engine/api/vms/" + VMUUID + "/statistics/" + memTotalUUID
  2090. //fmt.Println("Url:" ,url)
  2091. method := "GET"
  2092. client := &http.Client{}
  2093. req, err := http.NewRequest(method, url, nil)
  2094. if err != nil {
  2095. return "", -1, -1, errors.New("unexpected Error")
  2096. }
  2097. req.Header.Add("Version", "4")
  2098. req.Header.Add("Accept", "application/json")
  2099. req.Header.Add("Authorization", BA)
  2100. res, err := client.Do(req)
  2101. body, err := ioutil.ReadAll(res.Body)
  2102. defer res.Body.Close()
  2103. memUsage := ItemUsage{}
  2104. _err := json.Unmarshal(body, &memUsage)
  2105. if _err != nil {
  2106. fmt.Println("Error in vmStatistics 6: ", _err)
  2107. fmt.Println("Error: ", string(body))
  2108. return "", -1, -1, errors.New("unexpected Error")
  2109. }
  2110. memTotal = fmt.Sprintf("%f", memUsage.Values.Value[0].Datum)
  2111. }
  2112. //fmt.Println("CPU:" ,cpu)
  2113. //fmt.Println("MEM:", memUsed)
  2114. //fmt.Println("MEM:", memTotal)
  2115. _memusage, _ := strconv.ParseFloat(memUsed, 32)
  2116. _memtotal, _ := strconv.ParseFloat(memTotal, 32)
  2117. mem := _memusage / _memtotal
  2118. _cpu, _ := strconv.ParseFloat(cpu, 64)
  2119. return strings.Join(_disk, ", "), _cpu, mem, nil
  2120. }
  2121. func (o ovirt) vmDetails(c echo.Context) error {
  2122. //name,...,traffic,ip,status
  2123. user := c.Get("user").(*jwt.Token)
  2124. claims := user.Claims.(jwt.MapClaims)
  2125. _sha256 := sha256.Sum256([]byte(string(claims["name"].(string))))
  2126. var hashChannel_ = make(chan []byte, 1)
  2127. hashChannel_ <- _sha256[:]
  2128. token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
  2129. _BA := strings.Split(token, ";")
  2130. BA := _BA[len(_BA)-2]
  2131. uuid := c.FormValue("uuid")
  2132. if len(uuid) < 5 {
  2133. resp := _response{
  2134. Origin: "vmDetails",
  2135. Message: "Missing UUID",
  2136. Code: 1001,
  2137. }
  2138. return c.JSON(http.StatusNotFound, resp)
  2139. }
  2140. type vmStatus struct {
  2141. NextRunConfigurationExists string `json:"next_run_configuration_exists"`
  2142. NumaTuneMode string `json:"numa_tune_mode"`
  2143. Status string `json:"status"`
  2144. StopTime int64 `json:"stop_time"`
  2145. OriginalTemplate struct {
  2146. Href string `json:"href"`
  2147. ID string `json:"id"`
  2148. } `json:"original_template"`
  2149. Template struct {
  2150. Href string `json:"href"`
  2151. ID string `json:"id"`
  2152. } `json:"template"`
  2153. Actions struct {
  2154. Link []struct {
  2155. Href string `json:"href"`
  2156. Rel string `json:"rel"`
  2157. } `json:"link"`
  2158. } `json:"actions"`
  2159. Name string `json:"name"`
  2160. Description string `json:"description"`
  2161. Comment string `json:"comment"`
  2162. Href string `json:"href"`
  2163. ID string `json:"id"`
  2164. Bios struct {
  2165. BootMenu struct {
  2166. Enabled string `json:"enabled"`
  2167. } `json:"boot_menu"`
  2168. Type string `json:"type"`
  2169. } `json:"bios"`
  2170. CPU struct {
  2171. Architecture string `json:"architecture"`
  2172. Topology struct {
  2173. Cores string `json:"cores"`
  2174. Sockets string `json:"sockets"`
  2175. Threads string `json:"threads"`
  2176. } `json:"topology"`
  2177. } `json:"cpu"`
  2178. Display struct {
  2179. AllowOverride string `json:"allow_override"`
  2180. CopyPasteEnabled string `json:"copy_paste_enabled"`
  2181. DisconnectAction string `json:"disconnect_action"`
  2182. FileTransferEnabled string `json:"file_transfer_enabled"`
  2183. Monitors string `json:"monitors"`
  2184. SingleQxlPci string `json:"single_qxl_pci"`
  2185. SmartcardEnabled string `json:"smartcard_enabled"`
  2186. Type string `json:"type"`
  2187. } `json:"display"`
  2188. Initialization struct {
  2189. AuthorizedSSHKeys string `json:"authorized_ssh_keys"`
  2190. CloudInitNetworkProtocol string `json:"cloud_init_network_protocol"`
  2191. CustomScript string `json:"custom_script"`
  2192. HostName string `json:"host_name"`
  2193. NicConfigurations struct {
  2194. } `json:"nic_configurations"`
  2195. RegenerateSSHKeys string `json:"regenerate_ssh_keys"`
  2196. UserName string `json:"user_name"`
  2197. } `json:"initialization"`
  2198. Io struct {
  2199. Threads string `json:"threads"`
  2200. } `json:"io"`
  2201. Memory string `json:"memory"`
  2202. Migration struct {
  2203. AutoConverge string `json:"auto_converge"`
  2204. Compressed string `json:"compressed"`
  2205. Encrypted string `json:"encrypted"`
  2206. } `json:"migration"`
  2207. Origin string `json:"origin"`
  2208. Os struct {
  2209. Boot struct {
  2210. Devices struct {
  2211. Device []string `json:"device"`
  2212. } `json:"devices"`
  2213. } `json:"boot"`
  2214. Type string `json:"type"`
  2215. } `json:"os"`
  2216. Sso struct {
  2217. Methods struct {
  2218. Method []struct {
  2219. ID string `json:"id"`
  2220. } `json:"method"`
  2221. } `json:"methods"`
  2222. } `json:"sso"`
  2223. Stateless string `json:"stateless"`
  2224. Type string `json:"type"`
  2225. Usb struct {
  2226. Enabled string `json:"enabled"`
  2227. } `json:"usb"`
  2228. Cluster struct {
  2229. Href string `json:"href"`
  2230. ID string `json:"id"`
  2231. } `json:"cluster"`
  2232. Quota struct {
  2233. ID string `json:"id"`
  2234. } `json:"quota"`
  2235. Link []struct {
  2236. Href string `json:"href"`
  2237. Rel string `json:"rel"`
  2238. } `json:"link"`
  2239. CPUShares string `json:"cpu_shares"`
  2240. CreationTime int64 `json:"creation_time"`
  2241. DeleteProtected string `json:"delete_protected"`
  2242. HighAvailability struct {
  2243. Enabled string `json:"enabled"`
  2244. Priority string `json:"priority"`
  2245. } `json:"high_availability"`
  2246. LargeIcon struct {
  2247. Href string `json:"href"`
  2248. ID string `json:"id"`
  2249. } `json:"large_icon"`
  2250. MemoryPolicy struct {
  2251. Ballooning string `json:"ballooning"`
  2252. Guaranteed string `json:"guaranteed"`
  2253. Max string `json:"max"`
  2254. } `json:"memory_policy"`
  2255. MigrationDowntime string `json:"migration_downtime"`
  2256. MultiQueuesEnabled string `json:"multi_queues_enabled"`
  2257. PlacementPolicy struct {
  2258. Affinity string `json:"affinity"`
  2259. Hosts struct {
  2260. Host []struct {
  2261. Href string `json:"href"`
  2262. ID string `json:"id"`
  2263. } `json:"host"`
  2264. } `json:"hosts"`
  2265. } `json:"placement_policy"`
  2266. SmallIcon struct {
  2267. Href string `json:"href"`
  2268. ID string `json:"id"`
  2269. } `json:"small_icon"`
  2270. StartPaused string `json:"start_paused"`
  2271. StorageErrorResumeBehaviour string `json:"storage_error_resume_behaviour"`
  2272. TimeZone struct {
  2273. Name string `json:"name"`
  2274. } `json:"time_zone"`
  2275. CPUProfile struct {
  2276. Href string `json:"href"`
  2277. ID string `json:"id"`
  2278. } `json:"cpu_profile"`
  2279. }
  2280. //url := "https://ovirt-cl.zi-tel.com/ovirt-engine/api/vms/c1a44128-6c6c-406b-99d8-4a68a99380c9"
  2281. url := OvirtURL + "/ovirt-engine/api/vms/" + uuid
  2282. //fmt.Println("Url:" ,url)
  2283. method := "GET"
  2284. client := &http.Client{}
  2285. req, _ := http.NewRequest(method, url, nil)
  2286. //if err != nil {
  2287. // return "Null"
  2288. //}
  2289. req.Header.Add("Version", "4")
  2290. req.Header.Add("Accept", "application/json")
  2291. req.Header.Add("Authorization", BA)
  2292. res, _ := client.Do(req)
  2293. body, _ := ioutil.ReadAll(res.Body)
  2294. //fmt.Println("full response: ",string(body))
  2295. _vmstatus := vmStatus{}
  2296. _err := json.Unmarshal(body, &_vmstatus)
  2297. if _err != nil {
  2298. resp := _response{
  2299. Origin: "vmDetails",
  2300. Message: "Not Found",
  2301. Code: 1001,
  2302. }
  2303. return c.JSON(http.StatusNotFound, resp)
  2304. }
  2305. defer res.Body.Close()
  2306. // disk, cpu, ram, err := vmStatistics(BA, uuid)
  2307. cpuCore, _ := strconv.Atoi(_vmstatus.CPU.Topology.Cores)
  2308. cpuThread, _ := strconv.Atoi(_vmstatus.CPU.Topology.Threads)
  2309. cpuSocket, _ := strconv.Atoi(_vmstatus.CPU.Topology.Sockets)
  2310. cpu := cpuThread * cpuCore * cpuSocket
  2311. ram, _ := strconv.Atoi(_vmstatus.Memory)
  2312. diskStruct := listDisks(uuid, BA)
  2313. disk := 0
  2314. _size := 0
  2315. for _, v := range diskStruct {
  2316. _size, _ = strconv.Atoi(v.TotalSize)
  2317. }
  2318. disk += _size
  2319. nicStruct := listNIC(uuid, BA)
  2320. nic := len(nicStruct)
  2321. type JSONDetails struct {
  2322. Name string `json:"name"`
  2323. Value string `json:"value"`
  2324. Type string `json:"type"`
  2325. }
  2326. vmJsonDetails := [8]JSONDetails{}
  2327. {
  2328. db, err := sql.Open("mysql", MySQLUSER+":"+MySQLPASS+"@tcp(127.0.0.1:3306)/zicloud")
  2329. if err != nil {
  2330. resp := _response{
  2331. Origin: "vmDetails",
  2332. Message: "Not Found",
  2333. Code: 1001,
  2334. }
  2335. return c.JSON(http.StatusNotFound, resp)
  2336. }
  2337. defer db.Close()
  2338. results, err := db.Query("select details from service_profile where uuid='" + uuid + "'")
  2339. //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")
  2340. detailsStr := ""
  2341. for results.Next() {
  2342. _ = results.Scan(&detailsStr)
  2343. }
  2344. json.Unmarshal([]byte(detailsStr), &vmJsonDetails)
  2345. }
  2346. type AutoGenerated struct {
  2347. Message struct {
  2348. Disk string `json:"Disk"`
  2349. Memory string `json:"Memory"`
  2350. CPU string `json:"CPU"`
  2351. NIC string `json:"NIC"`
  2352. Traffic string `json:"Traffic"`
  2353. Status string `json:"Status"`
  2354. Period string `json:"Period"`
  2355. Name string `json:"Name"`
  2356. Template string `json:"Template"`
  2357. } `json:"message"`
  2358. Origin string `json:"origin"`
  2359. Code int `json:"code"`
  2360. }
  2361. resp := AutoGenerated{
  2362. Message: struct {
  2363. Disk string `json:"Disk"`
  2364. Memory string `json:"Memory"`
  2365. CPU string `json:"CPU"`
  2366. NIC string `json:"NIC"`
  2367. Traffic string `json:"Traffic"`
  2368. Status string `json:"Status"`
  2369. Period string `json:"Period"`
  2370. Name string `json:"Name"`
  2371. Template string `json:"Template"`
  2372. }{
  2373. Disk: fmt.Sprintf("%d", disk),
  2374. Memory: fmt.Sprintf("%d", ram),
  2375. CPU: fmt.Sprintf("%d", cpu),
  2376. NIC: fmt.Sprintf("%d", nic),
  2377. Traffic: vmJsonDetails[5].Value,
  2378. Status: _vmstatus.Status,
  2379. Period: "3",
  2380. // v.Name[len(login(BA).AuthenticatedUser.ID)+3:]
  2381. Name: _vmstatus.Name[len(login(BA).AuthenticatedUser.ID)+3:],
  2382. Template: vmJsonDetails[7].Value,
  2383. },
  2384. Origin: "vmDetails",
  2385. Code: 1000,
  2386. }
  2387. return c.JSON(http.StatusOK, resp)
  2388. //return _vmstatus.Status, _vmstatus.Name, disk, cpu, ram
  2389. }
  2390. func (o ovirt) ovirtPayment(c echo.Context) error {
  2391. invoiceUuid := c.FormValue("invoiceUuid")
  2392. db, err := sql.Open("mysql", MySQLUSER+":"+MySQLPASS+"@tcp(127.0.0.1:3306)/zicloud")
  2393. //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")
  2394. ///TODO: check duplicate payment confirmation by Invoice table
  2395. if err != nil {
  2396. }
  2397. update, err := db.Query("update scheduler set active='1' where related_uuid='" + invoiceUuid + "' and type=0")
  2398. defer db.Close()
  2399. if err != nil {
  2400. }
  2401. defer update.Close()
  2402. resp := _response{
  2403. Origin: "ovirt-ovirtPayment",
  2404. Message: "Done",
  2405. Code: 1000,
  2406. }
  2407. //b, _ := json.MarshalIndent(resp, "", " ")
  2408. //return c.String(http.StatusOK, string(b))
  2409. return c.JSON(http.StatusOK, resp)
  2410. }
  2411. func listNIC(VMUUID string, BA string) []struct {
  2412. Mac string `json:"mac"`
  2413. IPv4 string `json:"IPv4"`
  2414. IPv6 string `json:"IPv6"`
  2415. ReportedDevices struct {
  2416. Mac string `json:"mac"`
  2417. IPv4 string `json:"IPv4"`
  2418. IPv6 string `json:"IPv6"`
  2419. } `json:"reported_devices"`
  2420. } {
  2421. type NICList struct {
  2422. NIC []struct {
  2423. Mac string `json:"mac"`
  2424. IPv4 string `json:"IPv4"`
  2425. IPv6 string `json:"IPv6"`
  2426. ReportedDevices struct {
  2427. Mac string `json:"mac"`
  2428. IPv4 string `json:"IPv4"`
  2429. IPv6 string `json:"IPv6"`
  2430. } `json:"reported_devices"`
  2431. } `json:"NIC"`
  2432. }
  2433. type VMNIC struct {
  2434. Nic []struct {
  2435. Interface string `json:"interface"`
  2436. Linked string `json:"linked"`
  2437. Mac struct {
  2438. Address string `json:"address"`
  2439. } `json:"mac"`
  2440. Plugged string `json:"plugged"`
  2441. ReportedDevices struct {
  2442. ReportedDevice []struct {
  2443. Ips struct {
  2444. IP []struct {
  2445. Address string `json:"address"`
  2446. Version string `json:"version"`
  2447. } `json:"ip"`
  2448. } `json:"ips"`
  2449. Mac struct {
  2450. Address string `json:"address"`
  2451. } `json:"mac"`
  2452. Type string `json:"type"`
  2453. Name string `json:"name"`
  2454. Description string `json:"description"`
  2455. Href string `json:"href"`
  2456. ID string `json:"id"`
  2457. } `json:"reported_device"`
  2458. } `json:"reported_devices"`
  2459. VnicProfile struct {
  2460. Href string `json:"href"`
  2461. ID string `json:"id"`
  2462. } `json:"vnic_profile"`
  2463. Actions struct {
  2464. Link []struct {
  2465. Href string `json:"href"`
  2466. Rel string `json:"rel"`
  2467. } `json:"link"`
  2468. } `json:"actions"`
  2469. Name string `json:"name"`
  2470. Href string `json:"href"`
  2471. ID string `json:"id"`
  2472. VM struct {
  2473. Href string `json:"href"`
  2474. ID string `json:"id"`
  2475. } `json:"vm"`
  2476. Link []struct {
  2477. Href string `json:"href"`
  2478. Rel string `json:"rel"`
  2479. } `json:"link"`
  2480. } `json:"nic"`
  2481. }
  2482. url := "https://ovirt-cl.zi-tel.com/ovirt-engine/api/vms/" + VMUUID + "/nics"
  2483. method := "GET"
  2484. payload := strings.NewReader(``)
  2485. client := &http.Client{}
  2486. req, err := http.NewRequest(method, url, payload)
  2487. if err != nil {
  2488. //fmt.Println(err)
  2489. return nil
  2490. }
  2491. req.Header.Add("Version", "4")
  2492. req.Header.Add("Accept", "application/json")
  2493. req.Header.Add("Authorization", BA)
  2494. res, err := client.Do(req)
  2495. if err != nil {
  2496. //fmt.Println(err)
  2497. ///TODO: ErrorHandling
  2498. return nil
  2499. }
  2500. defer res.Body.Close()
  2501. body, err := ioutil.ReadAll(res.Body)
  2502. if err != nil {
  2503. //fmt.Println(err)
  2504. ///TODO: ErrorHandling
  2505. return nil
  2506. }
  2507. _VMNIC := VMNIC{}
  2508. err = json.Unmarshal(body, &_VMNIC)
  2509. //fmt.Println("ListNIC: res", string(body))
  2510. if err != nil {
  2511. ///TODO: ErrorHandling
  2512. //fmt.Println(err)
  2513. //return CPUPrice, memPrice, StoragePrice, IPPrice, extraBWPrice
  2514. }
  2515. _NICList := NICList{}
  2516. _Data := _NICList.NIC
  2517. x := struct {
  2518. Mac string `json:"mac"`
  2519. IPv4 string `json:"IPv4"`
  2520. IPv6 string `json:"IPv6"`
  2521. ReportedDevices struct {
  2522. Mac string `json:"mac"`
  2523. IPv4 string `json:"IPv4"`
  2524. IPv6 string `json:"IPv6"`
  2525. } `json:"reported_devices"`
  2526. }{}
  2527. for _, i := range _VMNIC.Nic {
  2528. x.IPv4 = "1.1.1.1"
  2529. ///TODO:GetAssignedIP from DHCP Table and remove this block
  2530. x.IPv6 = "Null"
  2531. x.Mac = i.Mac.Address
  2532. if len(i.ReportedDevices.ReportedDevice) > 0 {
  2533. x.ReportedDevices.Mac = i.ReportedDevices.ReportedDevice[0].Mac.Address
  2534. if len(i.ReportedDevices.ReportedDevice[0].Ips.IP) > 1 {
  2535. x.ReportedDevices.IPv4 = i.ReportedDevices.ReportedDevice[0].Ips.IP[0].Address
  2536. x.ReportedDevices.IPv6 = i.ReportedDevices.ReportedDevice[0].Ips.IP[1].Address
  2537. }
  2538. } else {
  2539. x.ReportedDevices.Mac = ""
  2540. x.ReportedDevices.IPv4 = ""
  2541. x.ReportedDevices.IPv6 = ""
  2542. }
  2543. _Data = append(_Data, x)
  2544. }
  2545. _NICList.NIC = _Data
  2546. return _NICList.NIC
  2547. }
  2548. func listDisks(VMUUID string, ba string) []struct {
  2549. Name string `json:"Name"`
  2550. TotalSize string `json:"TotalSize"`
  2551. ActualSize string `json:"ActualSize"`
  2552. } {
  2553. type DiskList struct {
  2554. Disk []struct {
  2555. Name string `json:"Name"`
  2556. TotalSize string `json:"TotalSize"`
  2557. ActualSize string `json:"ActualSize"`
  2558. } `json:"Disk"`
  2559. }
  2560. type ListDisks struct {
  2561. DiskAttachment []struct {
  2562. Active string `json:"active"`
  2563. Bootable string `json:"bootable"`
  2564. Interface string `json:"interface"`
  2565. LogicalName string `json:"logical_name"`
  2566. PassDiscard string `json:"pass_discard"`
  2567. ReadOnly string `json:"read_only"`
  2568. UsesScsiReservation string `json:"uses_scsi_reservation"`
  2569. Disk struct {
  2570. Href string `json:"href"`
  2571. ID string `json:"id"`
  2572. } `json:"disk"`
  2573. VM struct {
  2574. Href string `json:"href"`
  2575. ID string `json:"id"`
  2576. } `json:"vm"`
  2577. Href string `json:"href"`
  2578. ID string `json:"id"`
  2579. } `json:"disk_attachment"`
  2580. }
  2581. url := "https://ovirt-cl.zi-tel.com/ovirt-engine/api/vms/" + VMUUID + "/diskattachments"
  2582. method := "GET"
  2583. payload := strings.NewReader(``)
  2584. client := &http.Client{}
  2585. req, err := http.NewRequest(method, url, payload)
  2586. if err != nil {
  2587. //fmt.Println(err)
  2588. return nil
  2589. }
  2590. req.Header.Add("Version", "4")
  2591. req.Header.Add("Accept", "application/json")
  2592. req.Header.Add("Authorization", ba)
  2593. res, err := client.Do(req)
  2594. if err != nil {
  2595. //fmt.Println(err)
  2596. return nil
  2597. }
  2598. defer res.Body.Close()
  2599. body, err := ioutil.ReadAll(res.Body)
  2600. //fmt.Println("ListDisk: res", string(body))
  2601. if err != nil {
  2602. //fmt.Println(err)
  2603. return nil
  2604. }
  2605. _ListDisks := ListDisks{}
  2606. err = json.Unmarshal(body, &_ListDisks)
  2607. if err != nil {
  2608. //fmt.Println(err)
  2609. return nil
  2610. }
  2611. _DiskList := DiskList{}
  2612. for _, v := range _ListDisks.DiskAttachment {
  2613. _DiskList.Disk = append(_DiskList.Disk, DiskDetails(v.Disk.ID, ba))
  2614. }
  2615. return _DiskList.Disk
  2616. }
  2617. func DiskDetails(id string, ba string) struct {
  2618. Name string `json:"Name"`
  2619. TotalSize string `json:"TotalSize"`
  2620. ActualSize string `json:"ActualSize"`
  2621. } {
  2622. type DiskDetail struct {
  2623. ActualSize string `json:"actual_size"`
  2624. Alias string `json:"alias"`
  2625. Backup string `json:"backup"`
  2626. ContentType string `json:"content_type"`
  2627. Format string `json:"format"`
  2628. ImageID string `json:"image_id"`
  2629. PropagateErrors string `json:"propagate_errors"`
  2630. ProvisionedSize string `json:"provisioned_size"`
  2631. QcowVersion string `json:"qcow_version"`
  2632. Shareable string `json:"shareable"`
  2633. Sparse string `json:"sparse"`
  2634. Status string `json:"status"`
  2635. StorageType string `json:"storage_type"`
  2636. TotalSize string `json:"total_size"`
  2637. WipeAfterDelete string `json:"wipe_after_delete"`
  2638. DiskProfile struct {
  2639. Href string `json:"href"`
  2640. ID string `json:"id"`
  2641. } `json:"disk_profile"`
  2642. Quota struct {
  2643. Href string `json:"href"`
  2644. ID string `json:"id"`
  2645. } `json:"quota"`
  2646. StorageDomains struct {
  2647. StorageDomain []struct {
  2648. Href string `json:"href"`
  2649. ID string `json:"id"`
  2650. } `json:"storage_domain"`
  2651. } `json:"storage_domains"`
  2652. Actions struct {
  2653. Link []struct {
  2654. Href string `json:"href"`
  2655. Rel string `json:"rel"`
  2656. } `json:"link"`
  2657. } `json:"actions"`
  2658. Name string `json:"name"`
  2659. Description string `json:"description"`
  2660. Href string `json:"href"`
  2661. ID string `json:"id"`
  2662. Link []struct {
  2663. Href string `json:"href"`
  2664. Rel string `json:"rel"`
  2665. } `json:"link"`
  2666. }
  2667. //fmt.Println("List Disk: ",id)
  2668. url := "https://ovirt-cl.zi-tel.com/ovirt-engine/api/disks/" + id
  2669. method := "GET"
  2670. payload := strings.NewReader(``)
  2671. client := &http.Client{}
  2672. req, err := http.NewRequest(method, url, payload)
  2673. if err != nil {
  2674. //fmt.Println(err)
  2675. }
  2676. req.Header.Add("Version", "4")
  2677. req.Header.Add("Accept", "application/json")
  2678. req.Header.Add("Authorization", ba)
  2679. res, err := client.Do(req)
  2680. if err != nil {
  2681. //fmt.Println(err)
  2682. }
  2683. defer res.Body.Close()
  2684. body, err := ioutil.ReadAll(res.Body)
  2685. if err != nil {
  2686. //fmt.Println(err)
  2687. }
  2688. _DiskDetail := DiskDetail{}
  2689. err = json.Unmarshal(body, &_DiskDetail)
  2690. if err != nil {
  2691. //fmt.Println(err)
  2692. }
  2693. Disk := struct {
  2694. Name string `json:"Name"`
  2695. TotalSize string `json:"TotalSize"`
  2696. ActualSize string `json:"ActualSize"`
  2697. }{
  2698. Name: _DiskDetail.Alias,
  2699. TotalSize: _DiskDetail.ProvisionedSize,
  2700. ActualSize: _DiskDetail.ActualSize,
  2701. }
  2702. return Disk
  2703. }
  2704. func (o ovirt) VNC(c echo.Context) error {
  2705. type graphicConsoleList struct {
  2706. GraphicsConsole []struct {
  2707. Protocol string `json:"protocol"`
  2708. VM struct {
  2709. Href string `json:"href"`
  2710. ID string `json:"id"`
  2711. } `json:"vm"`
  2712. Actions struct {
  2713. Link []struct {
  2714. Href string `json:"href"`
  2715. Rel string `json:"rel"`
  2716. } `json:"link"`
  2717. } `json:"actions"`
  2718. Href string `json:"href"`
  2719. ID string `json:"id"`
  2720. } `json:"graphics_console"`
  2721. }
  2722. type vnc struct {
  2723. RemoteViewerConnectionFile string `json:"remote_viewer_connection_file"`
  2724. }
  2725. user := c.Get("user").(*jwt.Token)
  2726. claims := user.Claims.(jwt.MapClaims)
  2727. _sha256 := sha256.Sum256([]byte(string(claims["name"].(string))))
  2728. var hashChannel_ = make(chan []byte, 1)
  2729. hashChannel_ <- _sha256[:]
  2730. token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
  2731. _BA := strings.Split(token, ";")
  2732. BA := _BA[len(_BA)-2]
  2733. vmuuid := c.FormValue("VmUUID")
  2734. urlgraphiclist := OvirtURL + "/ovirt-engine/api/vms/" + vmuuid + "/graphicsconsoles"
  2735. client := &http.Client{}
  2736. req, err := http.NewRequest("Get", urlgraphiclist, nil)
  2737. if err != nil {
  2738. fmt.Println(err)
  2739. }
  2740. req.Header.Add("Version", "4")
  2741. req.Header.Add("Accept", "application/json")
  2742. req.Header.Add("Authorization", BA)
  2743. res, err := client.Do(req)
  2744. body, err := ioutil.ReadAll(res.Body)
  2745. defer res.Body.Close()
  2746. _graphicConsoleList := graphicConsoleList{
  2747. GraphicsConsole: []struct {
  2748. Protocol string "json:\"protocol\""
  2749. VM struct {
  2750. Href string "json:\"href\""
  2751. ID string "json:\"id\""
  2752. } "json:\"vm\""
  2753. Actions struct {
  2754. Link []struct {
  2755. Href string "json:\"href\""
  2756. Rel string "json:\"rel\""
  2757. } "json:\"link\""
  2758. } "json:\"actions\""
  2759. Href string "json:\"href\""
  2760. ID string "json:\"id\""
  2761. }{},
  2762. }
  2763. err = json.Unmarshal(body, &_graphicConsoleList)
  2764. urlvncfile := OvirtURL + "/ovirt-engine/api/vms/" + vmuuid + "/graphicsconsoles/" + _graphicConsoleList.GraphicsConsole[0].ID + "/remoteviewerconnectionfile"
  2765. client2 := &http.Client{}
  2766. payload := strings.NewReader(`{
  2767. }`)
  2768. req2, err := http.NewRequest("POST", urlvncfile, payload)
  2769. req2.Header.Add("Version", "4")
  2770. req2.Header.Add("Accept", "application/json")
  2771. req2.Header.Add("Content-Type", "application/json")
  2772. req2.Header.Add("Authorization", BA)
  2773. res2, err := client2.Do(req2)
  2774. body2, err := ioutil.ReadAll(res2.Body)
  2775. _vnc := vnc{}
  2776. err = json.Unmarshal(body2, &_vnc)
  2777. defer res2.Body.Close()
  2778. result := _vnc.RemoteViewerConnectionFile
  2779. dhost := strings.Split(result, "\n")[2]
  2780. dport := strings.Split(result, "\n")[3]
  2781. password := strings.Split(result, "\n")[4]
  2782. mrand.Seed(time.Now().UTC().UnixNano())
  2783. randInt := func(min, max int) int {
  2784. return min + mrand.Intn(max-min)
  2785. }
  2786. lport := randInt(5800, 6000)
  2787. {
  2788. app := "/root/novncRunner"
  2789. arg0 := fmt.Sprintf("%d", lport)
  2790. arg1 := strings.Split(dhost, "=")
  2791. arg2 := strings.Split(dport, "=")
  2792. exec.Command(app, arg2[1], arg1[1], arg0).Output()
  2793. }
  2794. resp := _response{
  2795. Origin: "ovirt-VNC",
  2796. Message: "https://vnc.zi-cloud.ir:" + fmt.Sprintf("%d", lport) + "/vnc.html?autoconnect=true&show_dot=true&password=" + strings.Split(password, "=")[1],
  2797. Code: 1000,
  2798. }
  2799. return c.JSON(http.StatusOK, resp)
  2800. }
  2801. func (o ovirt) listTemplate(c echo.Context) error {
  2802. type templateList struct {
  2803. Template []struct {
  2804. Status string `json:"status"`
  2805. Version struct {
  2806. VersionName string `json:"version_name"`
  2807. VersionNumber string `json:"version_number"`
  2808. BaseTemplate struct {
  2809. Href string `json:"href"`
  2810. ID string `json:"id"`
  2811. } `json:"base_template"`
  2812. } `json:"version"`
  2813. Actions struct {
  2814. Link []struct {
  2815. Href string `json:"href"`
  2816. Rel string `json:"rel"`
  2817. } `json:"link"`
  2818. } `json:"actions"`
  2819. Name string `json:"name"`
  2820. Description string `json:"description"`
  2821. Comment string `json:"comment"`
  2822. Href string `json:"href"`
  2823. ID string `json:"id"`
  2824. Bios struct {
  2825. BootMenu struct {
  2826. Enabled string `json:"enabled"`
  2827. } `json:"boot_menu"`
  2828. Type string `json:"type"`
  2829. } `json:"bios"`
  2830. CPU struct {
  2831. Architecture string `json:"architecture"`
  2832. Topology struct {
  2833. Cores string `json:"cores"`
  2834. Sockets string `json:"sockets"`
  2835. Threads string `json:"threads"`
  2836. } `json:"topology"`
  2837. } `json:"cpu"`
  2838. Display struct {
  2839. AllowOverride string `json:"allow_override"`
  2840. CopyPasteEnabled string `json:"copy_paste_enabled"`
  2841. DisconnectAction string `json:"disconnect_action"`
  2842. FileTransferEnabled string `json:"file_transfer_enabled"`
  2843. Monitors string `json:"monitors"`
  2844. SingleQxlPci string `json:"single_qxl_pci"`
  2845. SmartcardEnabled string `json:"smartcard_enabled"`
  2846. Type string `json:"type"`
  2847. } `json:"display"`
  2848. Io struct {
  2849. Threads string `json:"threads"`
  2850. } `json:"io"`
  2851. Memory string `json:"memory"`
  2852. Migration struct {
  2853. AutoConverge string `json:"auto_converge"`
  2854. Compressed string `json:"compressed"`
  2855. Encrypted string `json:"encrypted"`
  2856. } `json:"migration"`
  2857. Origin string `json:"origin"`
  2858. Os struct {
  2859. Boot struct {
  2860. Devices struct {
  2861. Device []string `json:"device"`
  2862. } `json:"devices"`
  2863. } `json:"boot"`
  2864. Type string `json:"type"`
  2865. } `json:"os"`
  2866. Sso struct {
  2867. Methods struct {
  2868. Method []struct {
  2869. ID string `json:"id"`
  2870. } `json:"method"`
  2871. } `json:"methods"`
  2872. } `json:"sso"`
  2873. Stateless string `json:"stateless"`
  2874. Type string `json:"type"`
  2875. Usb struct {
  2876. Enabled string `json:"enabled"`
  2877. } `json:"usb"`
  2878. Link []struct {
  2879. Href string `json:"href"`
  2880. Rel string `json:"rel"`
  2881. } `json:"link"`
  2882. CPUShares string `json:"cpu_shares"`
  2883. CreationTime int64 `json:"creation_time"`
  2884. DeleteProtected string `json:"delete_protected"`
  2885. HighAvailability struct {
  2886. Enabled string `json:"enabled"`
  2887. Priority string `json:"priority"`
  2888. } `json:"high_availability"`
  2889. LargeIcon struct {
  2890. Href string `json:"href"`
  2891. ID string `json:"id"`
  2892. } `json:"large_icon"`
  2893. MemoryPolicy struct {
  2894. Guaranteed string `json:"guaranteed"`
  2895. Max string `json:"max"`
  2896. } `json:"memory_policy"`
  2897. MigrationDowntime string `json:"migration_downtime"`
  2898. MultiQueuesEnabled string `json:"multi_queues_enabled"`
  2899. PlacementPolicy struct {
  2900. Affinity string `json:"affinity"`
  2901. } `json:"placement_policy"`
  2902. SmallIcon struct {
  2903. Href string `json:"href"`
  2904. ID string `json:"id"`
  2905. } `json:"small_icon"`
  2906. StartPaused string `json:"start_paused"`
  2907. StorageErrorResumeBehaviour string `json:"storage_error_resume_behaviour"`
  2908. Cluster struct {
  2909. Href string `json:"href"`
  2910. ID string `json:"id"`
  2911. } `json:"cluster,omitempty"`
  2912. TimeZone struct {
  2913. Name string `json:"name"`
  2914. } `json:"time_zone,omitempty"`
  2915. CPUProfile struct {
  2916. Href string `json:"href"`
  2917. ID string `json:"id"`
  2918. } `json:"cpu_profile,omitempty"`
  2919. Initialization struct {
  2920. AuthorizedSSHKeys string `json:"authorized_ssh_keys"`
  2921. CloudInitNetworkProtocol string `json:"cloud_init_network_protocol"`
  2922. CustomScript string `json:"custom_script"`
  2923. HostName string `json:"host_name"`
  2924. NicConfigurations struct {
  2925. } `json:"nic_configurations"`
  2926. RegenerateSSHKeys string `json:"regenerate_ssh_keys"`
  2927. UserName string `json:"user_name"`
  2928. } `json:"initialization,omitempty"`
  2929. } `json:"template"`
  2930. }
  2931. type templateListResponse struct {
  2932. Data []struct {
  2933. Name string `json:"name"`
  2934. } `json:"Data"`
  2935. Message string `json:"message"`
  2936. Origin string `json:"origin"`
  2937. Code int `json:"code"`
  2938. }
  2939. user := c.Get("user").(*jwt.Token)
  2940. claims := user.Claims.(jwt.MapClaims)
  2941. _sha256 := sha256.Sum256([]byte(string(claims["name"].(string))))
  2942. var hashChannel_ = make(chan []byte, 1)
  2943. hashChannel_ <- _sha256[:]
  2944. token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
  2945. _BA := strings.Split(token, ";")
  2946. BA := _BA[len(_BA)-2]
  2947. url := OvirtURL + "/ovirt-engine/api/templates?filter=true&search=Cloud"
  2948. client := &http.Client{}
  2949. req, err := http.NewRequest("GET", url, nil)
  2950. if err != nil {
  2951. fmt.Println(err)
  2952. }
  2953. req.Header.Add("Version", "4")
  2954. req.Header.Add("Accept", "application/json")
  2955. req.Header.Add("Authorization", BA)
  2956. res, err := client.Do(req)
  2957. body, err := ioutil.ReadAll(res.Body)
  2958. defer res.Body.Close()
  2959. _templateList := templateList{}
  2960. err = json.Unmarshal(body, &_templateList)
  2961. //fmt.Println("resp:",string(body))
  2962. _templateListResponse := templateListResponse{
  2963. Data: nil,
  2964. Message: "Done",
  2965. Origin: "ListTemplate",
  2966. Code: 1000,
  2967. }
  2968. _Data := _templateListResponse.Data
  2969. y := struct {
  2970. Name string `json:"name"`
  2971. }{}
  2972. for _, v := range _templateList.Template {
  2973. y.Name = v.Name
  2974. _Data = append(_Data, y)
  2975. }
  2976. _templateListResponse.Data = _Data
  2977. return c.JSON(http.StatusOK, _templateListResponse)
  2978. //return c.String(http.StatusOK, string(b))
  2979. }
  2980. func (o ovirt) vmHistory(c echo.Context) error {
  2981. type VMStatistics struct {
  2982. Statistic []struct {
  2983. Kind string `json:"kind"`
  2984. Type string `json:"type"`
  2985. Unit string `json:"unit"`
  2986. Values struct {
  2987. Value []struct {
  2988. Datum int64 `json:"datum"`
  2989. } `json:"value"`
  2990. } `json:"values"`
  2991. VM struct {
  2992. Href string `json:"href"`
  2993. ID string `json:"id"`
  2994. } `json:"vm,omitempty"`
  2995. Name string `json:"name"`
  2996. Description string `json:"description"`
  2997. Href string `json:"href,omitempty"`
  2998. ID string `json:"id"`
  2999. } `json:"statistic"`
  3000. }
  3001. type VMStatisticsResponse struct {
  3002. Data []struct {
  3003. Kind string `json:"kind"`
  3004. Type string `json:"type"`
  3005. Unit string `json:"unit"`
  3006. Values struct {
  3007. Value []struct {
  3008. Datum int64 `json:"datum"`
  3009. } `json:"value"`
  3010. } `json:"values"`
  3011. Name string `json:"name"`
  3012. Description string `json:"description"`
  3013. //Href string `json:"href,omitempty"`
  3014. //ID string `json:"id"`
  3015. } `json:"statistic"`
  3016. Message string `json:"message"`
  3017. Origin string `json:"origin"`
  3018. Code int `json:"code"`
  3019. }
  3020. user := c.Get("user").(*jwt.Token)
  3021. claims := user.Claims.(jwt.MapClaims)
  3022. _sha256 := sha256.Sum256([]byte(string(claims["name"].(string))))
  3023. var hashChannel_ = make(chan []byte, 1)
  3024. hashChannel_ <- _sha256[:]
  3025. token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
  3026. _BA := strings.Split(token, ";")
  3027. BA := _BA[len(_BA)-2]
  3028. vmuuid := c.FormValue("VmUUID")
  3029. url := OvirtURL + "/ovirt-engine/api/vms/" + vmuuid + "/statistics"
  3030. client := &http.Client{}
  3031. req, err := http.NewRequest("GET", url, nil)
  3032. if err != nil {
  3033. fmt.Println(err)
  3034. }
  3035. req.Header.Add("Version", "4")
  3036. req.Header.Add("Accept", "application/json")
  3037. req.Header.Add("Authorization", BA)
  3038. res, err := client.Do(req)
  3039. body, err := ioutil.ReadAll(res.Body)
  3040. defer res.Body.Close()
  3041. _VMStatistics := VMStatistics{}
  3042. err = json.Unmarshal(body, &_VMStatistics)
  3043. _VMStatisticsResponse := VMStatisticsResponse{
  3044. Data: nil,
  3045. Message: "Done",
  3046. Origin: "vmHistory",
  3047. Code: 1000,
  3048. }
  3049. _Data := _VMStatisticsResponse.Data
  3050. y := struct {
  3051. Kind string `json:"kind"`
  3052. Type string `json:"type"`
  3053. Unit string `json:"unit"`
  3054. Values struct {
  3055. Value []struct {
  3056. Datum int64 `json:"datum"`
  3057. } `json:"value"`
  3058. } `json:"values"`
  3059. Name string `json:"name"`
  3060. Description string `json:"description"`
  3061. //Href string `json:"href,omitempty"`
  3062. //ID string `json:"id"`
  3063. }{}
  3064. for _, v := range _VMStatistics.Statistic {
  3065. y.Kind = v.Kind
  3066. y.Unit = v.Unit
  3067. y.Type = v.Type
  3068. y.Values = v.Values
  3069. y.Name = v.Name
  3070. y.Description = v.Description
  3071. _Data = append(_Data, y)
  3072. }
  3073. _VMStatisticsResponse.Data = _Data
  3074. return c.JSON(http.StatusOK, _VMStatisticsResponse)
  3075. }
  3076. func (o ovirt) SSHKeyGen(c echo.Context) error {
  3077. type SSHKeyGenResponse struct {
  3078. Message string `json:"message"`
  3079. Origin string `json:"origin"`
  3080. Code int `json:"code"`
  3081. }
  3082. user := c.Get("user").(*jwt.Token)
  3083. claims := user.Claims.(jwt.MapClaims)
  3084. email := fmt.Sprintf("%s", claims["mail"])
  3085. fmt.Println(email)
  3086. mrand.Seed(time.Now().Unix())
  3087. var output strings.Builder
  3088. //Only lowercase
  3089. charSet := "abcdedfghijklmnopqrstABCDEFGHIJKLMNOP0123456789"
  3090. length := 20
  3091. for i := 0; i < length; i++ {
  3092. random := mrand.Intn(len(charSet))
  3093. randomChar := charSet[random]
  3094. output.WriteString(string(randomChar))
  3095. }
  3096. publicKeyBlock := &pem.Block{}
  3097. {
  3098. // generate key
  3099. privatekey, err := rsa.GenerateKey(rand.Reader, 1024)
  3100. if err != nil {
  3101. fmt.Printf("Cannot generate RSA key\n")
  3102. //os.Exit(1)
  3103. }
  3104. publickey := &privatekey.PublicKey
  3105. // dump private key to file
  3106. var privateKeyBytes []byte = x509.MarshalPKCS1PrivateKey(privatekey)
  3107. privateKeyBlock := &pem.Block{
  3108. Type: "RSA PRIVATE KEY",
  3109. Bytes: privateKeyBytes,
  3110. }
  3111. privatePem, err := os.Create("/tmp/" + output.String() + "-private.pem")
  3112. if err != nil {
  3113. fmt.Printf("error when create private.pem: %s \n", err)
  3114. //os.Exit(1)
  3115. }
  3116. err = pem.Encode(privatePem, privateKeyBlock)
  3117. if err != nil {
  3118. fmt.Printf("error when encode private pem: %s \n", err)
  3119. //os.Exit(1)
  3120. }
  3121. // dump public key to file
  3122. publicKeyBytes, err := x509.MarshalPKIXPublicKey(publickey)
  3123. if err != nil {
  3124. fmt.Printf("error when dumping publickey: %s \n", err)
  3125. //os.Exit(1)
  3126. }
  3127. publicKeyBlock = &pem.Block{
  3128. Type: "PUBLIC KEY",
  3129. Bytes: publicKeyBytes,
  3130. }
  3131. publicPem, err := os.Create("/tmp/" + output.String() + "-public.pem")
  3132. if err != nil {
  3133. fmt.Printf("error when create public.pem: %s \n", err)
  3134. //os.Exit(1)
  3135. }
  3136. err = pem.Encode(publicPem, publicKeyBlock)
  3137. if err != nil {
  3138. fmt.Printf("error when encode public pem: %s \n", err)
  3139. //os.Exit(1)
  3140. }
  3141. 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"})
  3142. }
  3143. _SSHKeyGenResponse := SSHKeyGenResponse{
  3144. Message: string(pem.EncodeToMemory(publicKeyBlock)),
  3145. Origin: "SSHKeyGen",
  3146. Code: 1000,
  3147. }
  3148. return c.JSON(http.StatusOK, _SSHKeyGenResponse)
  3149. }
  3150. func (o ovirt) ovirtSuspend(c echo.Context) error {
  3151. type VMSuspend struct {
  3152. Async string `json:"async"`
  3153. Job struct {
  3154. Href string `json:"href"`
  3155. ID string `json:"id"`
  3156. } `json:"job"`
  3157. Status string `json:"status"`
  3158. Href string `json:"href"`
  3159. ID string `json:"id"`
  3160. Link []struct {
  3161. Href string `json:"href"`
  3162. Rel string `json:"rel"`
  3163. } `json:"link"`
  3164. }
  3165. vmuuid := c.FormValue("VmUUID")
  3166. user := c.Get("user").(*jwt.Token)
  3167. claims := user.Claims.(jwt.MapClaims)
  3168. _sha256 := sha256.Sum256([]byte(string(claims["name"].(string))))
  3169. var hashChannel_ = make(chan []byte, 1)
  3170. hashChannel_ <- _sha256[:]
  3171. token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
  3172. _BA := strings.Split(token, ";")
  3173. BA := _BA[len(_BA)-2]
  3174. url := OvirtURL + "/ovirt-engine/api/vms/" + vmuuid + "/suspend"
  3175. method := "POST"
  3176. payload := strings.NewReader(`{
  3177. "async":"true"
  3178. }`)
  3179. client := &http.Client{}
  3180. req, err := http.NewRequest(method, url, payload)
  3181. if err != nil {
  3182. fmt.Println(err)
  3183. }
  3184. req.Header.Add("Version", "4")
  3185. req.Header.Add("Accept", "application/json")
  3186. ///TODO: BA
  3187. req.Header.Add("Authorization", BA)
  3188. req.Header.Add("Content-Type", "application/json")
  3189. res, err := client.Do(req)
  3190. if err != nil {
  3191. fmt.Println("Error 1", err)
  3192. }
  3193. defer res.Body.Close()
  3194. body, err := ioutil.ReadAll(res.Body)
  3195. //fmt.Println(res.Status)
  3196. //fmt.Println(res.Body)
  3197. if err != nil {
  3198. //fmt.Println("Error 3", err)
  3199. fmt.Println(err)
  3200. }
  3201. _VMSuspend := VMSuspend{}
  3202. err = json.Unmarshal(body, &_VMSuspend)
  3203. if err != nil {
  3204. //fmt.Println("Error 4", err)
  3205. fmt.Println(err)
  3206. }
  3207. //fmt.Println(_VMSuspend)
  3208. db, err := sql.Open("mysql", MySQLUSER+":"+MySQLPASS+"@tcp(127.0.0.1:3306)/zicloud")
  3209. if err != nil {
  3210. }
  3211. update, err := db.Query("update service_profile set active='-2' where uuid='" + vmuuid + "'")
  3212. defer db.Close()
  3213. if err != nil {
  3214. }
  3215. defer update.Close()
  3216. type VMSuspendResponse struct {
  3217. Message string `json:"message"`
  3218. Origin string `json:"origin"`
  3219. Code int `json:"code"`
  3220. }
  3221. resp := VMSuspendResponse{
  3222. Message: "Done",
  3223. Origin: "ovirtSuspend",
  3224. Code: 1000,
  3225. }
  3226. return c.JSON(http.StatusOK, resp)
  3227. }
  3228. func (o ovirt) BillingSuspend(c echo.Context) error {
  3229. type VMSuspend struct {
  3230. Async string `json:"async"`
  3231. Job struct {
  3232. Href string `json:"href"`
  3233. ID string `json:"id"`
  3234. } `json:"job"`
  3235. Status string `json:"status"`
  3236. Href string `json:"href"`
  3237. ID string `json:"id"`
  3238. Link []struct {
  3239. Href string `json:"href"`
  3240. Rel string `json:"rel"`
  3241. } `json:"link"`
  3242. }
  3243. vmuuid := c.FormValue("VmUUID")
  3244. //user := c.Get("user").(*jwt.Token)
  3245. //claims := user.Claims.(jwt.MapClaims)
  3246. //_sha256 := sha256.Sum256([]byte(string(claims["name"].(string))))
  3247. //var hashChannel_ = make(chan []byte, 1)
  3248. //hashChannel_ <- _sha256[:]
  3249. //token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
  3250. //_BA := strings.Split(token, ";")
  3251. //BA := _BA[len(_BA)-2]
  3252. url := OvirtURL + "/ovirt-engine/api/vms/" + vmuuid + "/suspend"
  3253. method := "POST"
  3254. payload := strings.NewReader(`{
  3255. "async":"true"
  3256. }`)
  3257. client := &http.Client{}
  3258. req, err := http.NewRequest(method, url, payload)
  3259. if err != nil {
  3260. fmt.Println(err)
  3261. }
  3262. req.Header.Add("Version", "4")
  3263. req.Header.Add("Accept", "application/json")
  3264. ///TODO: BA
  3265. req.Header.Add("Authorization", "Basic YWRtaW5AaW50ZXJuYWw6a2VsYW5zaCBqMw==")
  3266. req.Header.Add("Content-Type", "application/json")
  3267. res, err := client.Do(req)
  3268. if err != nil {
  3269. fmt.Println("Error 1", err)
  3270. }
  3271. defer res.Body.Close()
  3272. body, err := ioutil.ReadAll(res.Body)
  3273. //fmt.Println(res.Status)
  3274. //fmt.Println(res.Body)
  3275. if err != nil {
  3276. //fmt.Println("Error 3", err)
  3277. fmt.Println(err)
  3278. }
  3279. _VMSuspend := VMSuspend{}
  3280. err = json.Unmarshal(body, &_VMSuspend)
  3281. if err != nil {
  3282. //fmt.Println("Error 4", err)
  3283. fmt.Println(err)
  3284. }
  3285. //fmt.Println(_VMSuspend)
  3286. db, err := sql.Open("mysql", MySQLUSER+":"+MySQLPASS+"@tcp(127.0.0.1:3306)/zicloud")
  3287. if err != nil {
  3288. }
  3289. ///TODO: Sanitize Input variables
  3290. update, err := db.Query("update service_profile set active='-3' where uuid='" + vmuuid + "'")
  3291. defer db.Close()
  3292. if err != nil {
  3293. }
  3294. defer update.Close()
  3295. type VMSuspendResponse struct {
  3296. Message string `json:"message"`
  3297. Origin string `json:"origin"`
  3298. Code int `json:"code"`
  3299. }
  3300. resp := VMSuspendResponse{
  3301. Message: "Done",
  3302. Origin: "ovirtSuspend",
  3303. Code: 1000,
  3304. }
  3305. return c.JSON(http.StatusOK, resp)
  3306. }