1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034 |
- package main
- import (
- "crypto/rand"
- "crypto/rsa"
- "crypto/sha256"
- "crypto/x509"
- "database/sql"
- "encoding/json"
- "encoding/pem"
- "errors"
- "fmt"
- "io/ioutil"
- mrand "math/rand"
- "net/http"
- "os"
- "os/exec"
- "strconv"
- "strings"
- "time"
- "github.com/dgrijalva/jwt-go"
- _ "github.com/go-sql-driver/mysql"
- "github.com/labstack/echo"
- )
- type ovirt struct {
- }
- var MySQLUSER = "apigw"
- var MySQLPASS = "^_P+^7Q$bmPj+$xB"
- func login(BA string) OvirtObject {
- url := OvirtURL + "/ovirt-engine/api"
- method := "GET"
- client := &http.Client{}
- req, err := http.NewRequest(method, url, nil)
- if err != nil {
- fmt.Println(err)
- }
- req.Header.Add("Version", "4")
- req.Header.Add("Accept", "application/json")
- req.Header.Add("Authorization", BA)
- res, err := client.Do(req)
- body, err := ioutil.ReadAll(res.Body)
- defer res.Body.Close()
- object := OvirtObject{}
- err = json.Unmarshal(body, &object)
- return object
- }
- type OvirtObject struct {
- ProductInfo struct {
- Name string `json:"name"`
- Version struct {
- Build string `json:"build"`
- FullVersion string `json:"full_version"`
- Major string `json:"major"`
- Minor string `json:"minor"`
- Revision string `json:"revision"`
- } `json:"version"`
- } `json:"product_info"`
- SpecialObjects struct {
- BlankTemplate struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"blank_template"`
- RootTag struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"root_tag"`
- } `json:"special_objects"`
- Time int64 `json:"time"`
- AuthenticatedUser struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"authenticated_user"`
- EffectiveUser struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"effective_user"`
- Link []struct {
- Href string `json:"href"`
- Rel string `json:"rel"`
- } `json:"link"`
- }
- type TaskHeader struct {
- Name string `json:"Name,omitempty"`
- Value string `json:"Value,omitempty"`
- }
- type addVMTask struct {
- URL string `json:"url"`
- JSON string `json:__json`
- Method string `json:"method"`
- Headers []struct {
- Name string `json:"Name,omitempty"`
- Value string `json:"Value,omitempty"`
- } `json:"headers"`
- }
- type AddVMRequest struct {
- URL string `json:"url"`
- JSON struct {
- Name string `json:"name"`
- Description string `json:"description"`
- Comment string `json:"comment"`
- Cluster struct {
- Name string `json:"name"`
- } `json:"cluster"`
- Template struct {
- Name string `json:"name"`
- } `json:"template"`
- CPU struct {
- Topology struct {
- Sockets string `json:"sockets"`
- Cores string `json:"cores"`
- Threads string `json:"threads"`
- } `json:"topology"`
- } `json:"cpu"`
- Memory string `json:"memory"`
- MemoryPolicy struct {
- Ballooning string `json:"ballooning"`
- Guaranteed string `json:"guaranteed"`
- OverCommit struct {
- Percent string `json:"percent"`
- } `json:"over_commit"`
- } `json:"memory_policy"`
- } `json:"JSON"`
- Method string `json:"method"`
- Headers []struct {
- Name string `json:"Name"`
- Value string `json:"Value"`
- } `json:"headers"`
- }
- type VMStatistics struct {
- Statistic []struct {
- Kind string `json:"kind"`
- Type string `json:"type"`
- Unit string `json:"unit"`
- Values struct {
- Value []struct {
- Datum float64 `json:"datum"`
- } `json:"value"`
- } `json:"values"`
- VM struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"vm,omitempty"`
- Name string `json:"name"`
- Description string `json:"description"`
- Href string `json:"href,omitempty"`
- ID string `json:"id"`
- } `json:"statistic"`
- }
- func (o ovirt) vmStatus(uuid string) string {
- type vmStatus struct {
- NextRunConfigurationExists string `json:"next_run_configuration_exists"`
- NumaTuneMode string `json:"numa_tune_mode"`
- Status string `json:"status"`
- StopTime int64 `json:"stop_time"`
- OriginalTemplate struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"original_template"`
- Template struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"template"`
- Actions struct {
- Link []struct {
- Href string `json:"href"`
- Rel string `json:"rel"`
- } `json:"link"`
- } `json:"actions"`
- Name string `json:"name"`
- Description string `json:"description"`
- Comment string `json:"comment"`
- Href string `json:"href"`
- ID string `json:"id"`
- Bios struct {
- BootMenu struct {
- Enabled string `json:"enabled"`
- } `json:"boot_menu"`
- Type string `json:"type"`
- } `json:"bios"`
- CPU struct {
- Architecture string `json:"architecture"`
- Topology struct {
- Cores string `json:"cores"`
- Sockets string `json:"sockets"`
- Threads string `json:"threads"`
- } `json:"topology"`
- } `json:"cpu"`
- Display struct {
- AllowOverride string `json:"allow_override"`
- CopyPasteEnabled string `json:"copy_paste_enabled"`
- DisconnectAction string `json:"disconnect_action"`
- FileTransferEnabled string `json:"file_transfer_enabled"`
- Monitors string `json:"monitors"`
- SingleQxlPci string `json:"single_qxl_pci"`
- SmartcardEnabled string `json:"smartcard_enabled"`
- Type string `json:"type"`
- } `json:"display"`
- Initialization struct {
- AuthorizedSSHKeys string `json:"authorized_ssh_keys"`
- CloudInitNetworkProtocol string `json:"cloud_init_network_protocol"`
- CustomScript string `json:"custom_script"`
- HostName string `json:"host_name"`
- NicConfigurations struct {
- } `json:"nic_configurations"`
- RegenerateSSHKeys string `json:"regenerate_ssh_keys"`
- UserName string `json:"user_name"`
- } `json:"initialization"`
- Io struct {
- Threads string `json:"threads"`
- } `json:"io"`
- Memory string `json:"memory"`
- Migration struct {
- AutoConverge string `json:"auto_converge"`
- Compressed string `json:"compressed"`
- Encrypted string `json:"encrypted"`
- } `json:"migration"`
- Origin string `json:"origin"`
- Os struct {
- Boot struct {
- Devices struct {
- Device []string `json:"device"`
- } `json:"devices"`
- } `json:"boot"`
- Type string `json:"type"`
- } `json:"os"`
- Sso struct {
- Methods struct {
- Method []struct {
- ID string `json:"id"`
- } `json:"method"`
- } `json:"methods"`
- } `json:"sso"`
- Stateless string `json:"stateless"`
- Type string `json:"type"`
- Usb struct {
- Enabled string `json:"enabled"`
- } `json:"usb"`
- Cluster struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"cluster"`
- Quota struct {
- ID string `json:"id"`
- } `json:"quota"`
- Link []struct {
- Href string `json:"href"`
- Rel string `json:"rel"`
- } `json:"link"`
- CPUShares string `json:"cpu_shares"`
- CreationTime int64 `json:"creation_time"`
- DeleteProtected string `json:"delete_protected"`
- HighAvailability struct {
- Enabled string `json:"enabled"`
- Priority string `json:"priority"`
- } `json:"high_availability"`
- LargeIcon struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"large_icon"`
- MemoryPolicy struct {
- Ballooning string `json:"ballooning"`
- Guaranteed string `json:"guaranteed"`
- Max string `json:"max"`
- } `json:"memory_policy"`
- MigrationDowntime string `json:"migration_downtime"`
- MultiQueuesEnabled string `json:"multi_queues_enabled"`
- PlacementPolicy struct {
- Affinity string `json:"affinity"`
- Hosts struct {
- Host []struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"host"`
- } `json:"hosts"`
- } `json:"placement_policy"`
- SmallIcon struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"small_icon"`
- StartPaused string `json:"start_paused"`
- StorageErrorResumeBehaviour string `json:"storage_error_resume_behaviour"`
- TimeZone struct {
- Name string `json:"name"`
- } `json:"time_zone"`
- CPUProfile struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"cpu_profile"`
- }
- //url := "https://ovirt-cl.zi-tel.com/ovirt-engine/api/vms/c1a44128-6c6c-406b-99d8-4a68a99380c9"
- url := OvirtURL + "/ovirt-engine/api/vms/" + uuid
- //fmt.Println("VMSTATUS UUID:" ,uuid)
- method := "GET"
- client := &http.Client{}
- req, err := http.NewRequest(method, url, nil)
- if err != nil {
- fmt.Println("Error in vmStatus ", err)
- //return "Null"
- }
- req.Header.Add("Version", "4")
- req.Header.Add("Accept", "application/json")
- //fmt.Println("in vmStatus 1 " )
- //TODO: replace BA
- req.Header.Add("Authorization", "Basic YWRtaW5AaW50ZXJuYWw6a2VsYW5zaCBqMw==")
- //fmt.Println("in vmStatus 1 2 " )
- res, err := client.Do(req)
- //fmt.Println("in vmStatus :",err )
- if err != nil {
- fmt.Println("Error in vmStatus ", err)
- //return "Null"
- }
- defer res.Body.Close()
- //fmt.Println("in vmStatus 3 " )
- body, err := ioutil.ReadAll(res.Body)
- if err != nil {
- fmt.Println("Error in vmStatus ", err)
- //return "Null"
- }
- //fmt.Println("full response: ",string(body))
- //fmt.Println("in vmStatus 4 " )
- _vmstatus := vmStatus{}
- _err := json.Unmarshal(body, &_vmstatus)
- //fmt.Println("in vmStatus 5 " )
- if _err != nil {
- fmt.Println("Error in vmStatus ", _err)
- }
- return _vmstatus.Status
- }
- func (o ovirt) addvm(c echo.Context) error {
- type VMDescr struct {
- VMName string `json:"vmname"`
- VMCpu string `json:"vmCpu"`
- VMMem string `json:"vmMem"`
- VMNIC string `json:"vmnic"`
- VMBW string `json:"vmbw"`
- VMUUID string `json:"vmuuid"`
- Invoice string `json:"invoice"`
- }
- type AddVMPayment struct {
- Data struct {
- Price struct {
- CPU float64 `json:"cpu"`
- Mem float64 `json:"mem"`
- Disk float64 `json:"disk"`
- Nic float64 `json:"nic"`
- BW float64 `json:"bw"`
- SUM float64 `json:"sum"`
- SUMRaw float64 `json:"SUMRaw"`
- Period string `json:"period"`
- } `json:"price"`
- InvoiceUUID string `json:"invoiceUUID"`
- } `json:"data"`
- Message string `json:"message"`
- Origin string `json:"origin"`
- Code int `json:"code"`
- }
- user := c.Get("user").(*jwt.Token)
- claims := user.Claims.(jwt.MapClaims)
- _sha256 := sha256.Sum256([]byte(string(claims["name"].(string))))
- var hashChannel_ = make(chan []byte, 1)
- hashChannel_ <- _sha256[:]
- token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
- _BA := strings.Split(token, ";")
- BA := _BA[len(_BA)-2]
- var vmname, vmdescr, vmcomment, templatename, cpuSock, cpuCore, cpuThread, mem, Disk, nic, period, extraBW string
- coupon := 0
- vmname = login(BA).AuthenticatedUser.ID + "-_-" + c.FormValue("VmName")
- vmdescr = c.FormValue("VmDescr")
- vmcomment = c.FormValue("VmComment")
- templatename = c.FormValue("VmTempl")
- cpuThread = c.FormValue("VmCPU")
- Disk = c.FormValue("VmDisk")
- period = c.FormValue("VmPeriod")
- nic = c.FormValue("VmNIC")
- extraBW = c.FormValue("extraBW")
- sshKey := c.FormValue("sshKey")
- rootpass := c.FormValue("rootpass")
- coupon, _ = strconv.Atoi(c.FormValue("coupon"))
- cpuCore = "1"
- cpuSock = "1"
- mem = c.FormValue("VmMem")
- url := OvirtURL + "/ovirt-engine/api/vms"
- method := "POST"
- //addvmresponse := AddVMResponse{}O
- newvm := AddVMRequest{
- URL: url,
- JSON: struct {
- Name string `json:"name"`
- Description string `json:"description"`
- Comment string `json:"comment"`
- Cluster struct {
- Name string `json:"name"`
- } `json:"cluster"`
- Template struct {
- Name string `json:"name"`
- } `json:"template"`
- CPU struct {
- Topology struct {
- Sockets string `json:"sockets"`
- Cores string `json:"cores"`
- Threads string `json:"threads"`
- } `json:"topology"`
- } `json:"cpu"`
- Memory string `json:"memory"`
- MemoryPolicy struct {
- Ballooning string `json:"ballooning"`
- Guaranteed string `json:"guaranteed"`
- OverCommit struct {
- Percent string `json:"percent"`
- } `json:"over_commit"`
- } `json:"memory_policy"`
- }{
- Name: vmname,
- Description: vmdescr,
- Comment: vmcomment,
- Cluster: struct {
- Name string `json:"name"`
- }{Name: "Default"},
- Template: struct {
- Name string `json:"name"`
- }{Name: templatename},
- CPU: struct {
- Topology struct {
- Sockets string `json:"sockets"`
- Cores string `json:"cores"`
- Threads string `json:"threads"`
- } `json:"topology"`
- }{
- struct {
- Sockets string `json:"sockets"`
- Cores string `json:"cores"`
- Threads string `json:"threads"`
- }{
- Sockets: cpuSock,
- Cores: cpuCore,
- Threads: cpuThread,
- },
- },
- Memory: mem,
- MemoryPolicy: struct {
- Ballooning string `json:"ballooning"`
- Guaranteed string `json:"guaranteed"`
- OverCommit struct {
- Percent string `json:"percent"`
- } `json:"over_commit"`
- }{
- Ballooning: "true",
- Guaranteed: mem,
- OverCommit: struct {
- Percent string `json:"percent"`
- }{Percent: "10"},
- },
- },
- Method: method,
- Headers: nil,
- }
- newvm.Headers = append(newvm.Headers, struct {
- Name string `json:"Name"`
- Value string `json:"Value"`
- }{
- Name: "Accept",
- Value: "application/json",
- })
- newvm.Headers = append(newvm.Headers, struct {
- Name string `json:"Name"`
- Value string `json:"Value"`
- }{
- Name: "Authorization",
- Value: BA,
- })
- newvm.Headers = append(newvm.Headers, struct {
- Name string `json:"Name"`
- Value string `json:"Value"`
- }{
- Name: "Content-Type",
- Value: "application/json",
- })
- uuid, _ := uuidgen("APIGW-Ovirt-addVMTask")
- //invoiceUUID, _ := uuidgen("APIGW-FakeInvoice")
- CPUPrice, memPrice, StoragePrice, IPPrice, extraBWPrice, SUM, SUMRaw, invoiceUUID := IaaSCreate(login(BA).AuthenticatedUser.ID, period, cpuThread, mem, Disk, nic, extraBW, false, coupon)
- type JSONDetails struct {
- Name string `json:"name"`
- Value string `json:"value"`
- Type string `json:"type"`
- }
- _jsonDetail := [8]JSONDetails{}
- _jsonDetail[0].Name = "Period"
- _jsonDetail[0].Value = period
- _jsonDetail[0].Type = "int"
- _jsonDetail[1].Name = "cpuThread"
- _jsonDetail[1].Value = cpuThread
- _jsonDetail[1].Type = "int"
- _jsonDetail[2].Name = "mem"
- _jsonDetail[2].Value = mem
- _jsonDetail[2].Type = "int"
- _jsonDetail[3].Name = "Disk"
- _jsonDetail[3].Value = Disk
- _jsonDetail[3].Type = "int"
- _jsonDetail[4].Name = "nic"
- _jsonDetail[4].Value = nic
- _jsonDetail[4].Type = "int"
- _jsonDetail[5].Name = "extraBW"
- _jsonDetail[5].Value = extraBW
- _jsonDetail[5].Type = "int"
- _jsonDetail[6].Name = "coupon"
- _jsonDetail[6].Value = fmt.Sprintf("%d", coupon)
- _jsonDetail[6].Type = "int"
- _jsonDetail[7].Name = "Template"
- _jsonDetail[7].Value = templatename
- _jsonDetail[7].Type = "string"
- jsonDetail, _ := json.Marshal(_jsonDetail)
- responseInvoiece := AddVMPayment{
- Data: struct {
- Price struct {
- CPU float64 `json:"cpu"`
- Mem float64 `json:"mem"`
- Disk float64 `json:"disk"`
- Nic float64 `json:"nic"`
- BW float64 `json:"bw"`
- SUM float64 `json:"sum"`
- SUMRaw float64 `json:"SUMRaw"`
- Period string `json:"period"`
- } `json:"price"`
- InvoiceUUID string `json:"invoiceUUID"`
- }{
- Price: struct {
- CPU float64 `json:"cpu"`
- Mem float64 `json:"mem"`
- Disk float64 `json:"disk"`
- Nic float64 `json:"nic"`
- BW float64 `json:"bw"`
- SUM float64 `json:"sum"`
- SUMRaw float64 `json:"SUMRaw"`
- Period string `json:"period"`
- }{
- CPU: CPUPrice,
- Mem: memPrice,
- Disk: StoragePrice,
- Nic: IPPrice,
- BW: extraBWPrice,
- SUM: SUM,
- SUMRaw: SUMRaw,
- Period: period,
- },
- InvoiceUUID: invoiceUUID,
- },
- Message: "Done",
- Origin: "AddVM",
- Code: 1000,
- }
- if len(invoiceUUID) < 5 {
- resp := _response{
- Origin: "ovirt-addvm",
- Message: "Error on Invoice Calculation",
- Code: 1001,
- }
- b, _ := json.MarshalIndent(resp, "", " ")
- return c.String(http.StatusBadRequest, string(b))
- }
- fmt.Println("NewVM: ", newvm)
- __createVM, _ := json.MarshalIndent(newvm, "", " ")
- // Add VM Task
- addTask(uuid, string(__createVM), "", "APIGW", "VM Creation for "+claims["name"].(string), invoiceUUID, "0", "0")
- {
- db, err := sql.Open("mysql", MySQLUSER+":"+MySQLPASS+"@tcp(127.0.0.1:3306)/zicloud")
- if err != nil {
- resp := _response{
- Origin: "ovirt-addvm",
- Message: "Error on connecting db for save add vm result",
- Code: 1001,
- }
- b, _ := json.MarshalIndent(resp, "", " ")
- return c.String(http.StatusBadRequest, string(b))
- }
- defer db.Close()
- insert, err := db.Query("INSERT INTO service_profile VALUES ( '" + invoiceUUID + "'," +
- "'" + claims["IPAUid"].(string) + "'," +
- "'" + "VM" + "'," +
- "'" + "" + "'," +
- "'" + login(BA).AuthenticatedUser.ID + "'," +
- "NOW()" + "," +
- "NOW() ," +
- "-1" + "," +
- "'" + vmname + "'," +
- "'" + string(jsonDetail) + "'," +
- "'" + invoiceUUID + "' )")
- defer insert.Close()
- if err != nil {
- fmt.Println("Error in addVM: ", err.Error())
- }
- }
- // Start Task
- {
- url := OvirtURL + "/ovirt-engine/api/vms/" + invoiceUUID + "/start"
- method := "POST"
- nicAddress := "172.20.15.251"
- nicMask := "255.255.255.0"
- nicGW := "172.20.15.1"
- __json := fmt.Sprintf(`
- {
- "async":"true",
- "use_cloud_init": "true",
- "vm": {
- "initialization": {
- "authorized_ssh_keys": "%s",
- "host_name": "Sassan.local",
- "user_name": "root",
- "root_password": "%s",
- "nic_configurations": {
- "nic_configuration": [
- {
- "name": "eth0",
- "on_boot": "true",
- "boot_protocol": "static",
- "ip": {
- "address": "%s",
- "netmask": "%s",
- "gateway": "%s"
- }
- }
- ]
- },
- "dns_servers": "172.20.11.11"
- }
- }
- }
- `, sshKey, rootpass, nicAddress, nicMask, nicGW)
- sha256 := sha256.Sum256([]byte(invoiceUUID))
- var hashChannel = make(chan []byte, 1)
- hashChannel <- sha256[:]
- ___json := encrypt(<-hashChannel, __json)
- startVM := addVMTask{
- URL: url,
- JSON: ___json,
- Method: method,
- Headers: nil,
- }
- startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Version", Value: "4"})
- startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Accept", Value: "application/json"})
- startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Content-Type", Value: "application/json"})
- startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Authorization", Value: BA})
- uuid, _ := uuidgen("APIGW-Ovirt-CloudInit")
- __startVM, _ := json.MarshalIndent(startVM, "", " ")
- //fmt.Println("StartVMHeaders: ", string(__startVMHeaders))
- addTask(uuid, string(__startVM), "", "APIGW", "VM Initialization", invoiceUUID, "1", "0")
- }
- //resp := _response{
- // Origin: "ovirt-addvm",
- // Message: resposeInvoice
- // Code: 1000,
- //}
- return c.JSON(http.StatusOK, responseInvoiece)
- }
- func (o ovirt) listVM(c echo.Context) error {
- type listVMs struct {
- VM []struct {
- Fqdn string `json:"fqdn,omitempty"`
- GuestOperatingSystem struct {
- Architecture string `json:"architecture"`
- Codename string `json:"codename"`
- Distribution string `json:"distribution"`
- Family string `json:"family"`
- Kernel struct {
- Version struct {
- Build string `json:"build"`
- FullVersion string `json:"full_version"`
- Major string `json:"major"`
- Minor string `json:"minor"`
- Revision string `json:"revision"`
- } `json:"version"`
- } `json:"kernel"`
- Version struct {
- FullVersion string `json:"full_version"`
- Major string `json:"major"`
- } `json:"version"`
- } `json:"guest_operating_system,omitempty"`
- GuestTimeZone struct {
- Name string `json:"name"`
- UtcOffset string `json:"utc_offset"`
- } `json:"guest_time_zone,omitempty"`
- NextRunConfigurationExists string `json:"next_run_configuration_exists"`
- NumaTuneMode string `json:"numa_tune_mode"`
- RunOnce string `json:"run_once,omitempty"`
- StartTime int64 `json:"start_time,omitempty"`
- Status string `json:"status"`
- StopTime int64 `json:"stop_time"`
- OriginalTemplate struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"original_template"`
- Template struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"template"`
- Actions struct {
- Link []struct {
- Href string `json:"href"`
- Rel string `json:"rel"`
- } `json:"link"`
- } `json:"actions"`
- Name string `json:"name"`
- Description string `json:"description"`
- Comment string `json:"comment"`
- Href string `json:"href"`
- ID string `json:"id"`
- Bios struct {
- BootMenu struct {
- Enabled string `json:"enabled"`
- } `json:"boot_menu"`
- Type string `json:"type"`
- } `json:"bios"`
- CPU struct {
- Architecture string `json:"architecture"`
- Topology struct {
- Cores string `json:"cores"`
- Sockets string `json:"sockets"`
- Threads string `json:"threads"`
- } `json:"topology"`
- } `json:"cpu"`
- Display struct {
- Address string `json:"address"`
- AllowOverride string `json:"allow_override"`
- Certificate struct {
- Content string `json:"content"`
- Organization string `json:"organization"`
- Subject string `json:"subject"`
- } `json:"certificate"`
- CopyPasteEnabled string `json:"copy_paste_enabled"`
- DisconnectAction string `json:"disconnect_action"`
- FileTransferEnabled string `json:"file_transfer_enabled"`
- Monitors string `json:"monitors"`
- Port string `json:"port"`
- SecurePort string `json:"secure_port"`
- SingleQxlPci string `json:"single_qxl_pci"`
- SmartcardEnabled string `json:"smartcard_enabled"`
- Type string `json:"type"`
- } `json:"display"`
- Initialization struct {
- AuthorizedSSHKeys string `json:"authorized_ssh_keys"`
- CloudInitNetworkProtocol string `json:"cloud_init_network_protocol"`
- CustomScript string `json:"custom_script"`
- HostName string `json:"host_name"`
- NicConfigurations struct {
- } `json:"nic_configurations"`
- RegenerateSSHKeys string `json:"regenerate_ssh_keys"`
- UserName string `json:"user_name"`
- } `json:"initialization"`
- Io struct {
- Threads string `json:"threads"`
- } `json:"io"`
- Memory string `json:"memory"`
- Migration struct {
- AutoConverge string `json:"auto_converge"`
- Compressed string `json:"compressed"`
- Encrypted string `json:"encrypted"`
- } `json:"migration"`
- Origin string `json:"origin"`
- Os struct {
- Boot struct {
- Devices struct {
- Device []string `json:"device"`
- } `json:"devices"`
- } `json:"boot"`
- Type string `json:"type"`
- } `json:"os"`
- Sso struct {
- Methods struct {
- Method []struct {
- ID string `json:"id"`
- } `json:"method"`
- } `json:"methods"`
- } `json:"sso"`
- Stateless string `json:"stateless"`
- Type string `json:"type"`
- Usb struct {
- Enabled string `json:"enabled"`
- } `json:"usb"`
- Cluster struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"cluster"`
- Quota struct {
- ID string `json:"id"`
- } `json:"quota"`
- Link []struct {
- Href string `json:"href"`
- Rel string `json:"rel"`
- } `json:"link"`
- CPUShares string `json:"cpu_shares"`
- CreationTime int64 `json:"creation_time"`
- DeleteProtected string `json:"delete_protected"`
- HighAvailability struct {
- Enabled string `json:"enabled"`
- Priority string `json:"priority"`
- } `json:"high_availability"`
- LargeIcon struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"large_icon"`
- MemoryPolicy struct {
- Guaranteed string `json:"guaranteed"`
- Max string `json:"max"`
- } `json:"memory_policy"`
- MigrationDowntime string `json:"migration_downtime"`
- MultiQueuesEnabled string `json:"multi_queues_enabled"`
- SmallIcon struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"small_icon"`
- StartPaused string `json:"start_paused"`
- StorageErrorResumeBehaviour string `json:"storage_error_resume_behaviour"`
- TimeZone struct {
- Name string `json:"name"`
- } `json:"time_zone"`
- CPUProfile struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"cpu_profile"`
- StopReason string `json:"stop_reason,omitempty"`
- } `json:"vm"`
- }
- type listVMResponse struct {
- Data []struct {
- Fqdn string `json:"fqdn"`
- StartTime int64 `json:"start_time"`
- Status string `json:"status"`
- Name string `json:"name"`
- Description string `json:"description"`
- Comment string `json:"comment"`
- ID string `json:"id"`
- CPU struct {
- Topology struct {
- Cores string `json:"cores"`
- Sockets string `json:"sockets"`
- Threads string `json:"threads"`
- } `json:"topology"`
- } `json:"cpu"`
- Memory string `json:"memory"`
- CreationTime int64 `json:"creation_time"`
- Disk []struct {
- Name string `json:"Name"`
- TotalSize string `json:"TotalSize"`
- ActualSize string `json:"ActualSize"`
- } `json:"Disk"`
- NIC []struct {
- Mac string `json:"mac"`
- IPv4 string `json:"IPv4"`
- IPv6 string `json:"IPv6"`
- ReportedDevices struct {
- Mac string `json:"mac"`
- IPv4 string `json:"IPv4"`
- IPv6 string `json:"IPv6"`
- } `json:"reported_devices"`
- } `json:"NIC"`
- } `json:"vm"`
- Message string `json:"message"`
- Origin string `json:"origin"`
- Code int `json:"code"`
- }
- user := c.Get("user").(*jwt.Token)
- claims := user.Claims.(jwt.MapClaims)
- _sha256 := sha256.Sum256([]byte(string(claims["name"].(string))))
- var hashChannel_ = make(chan []byte, 1)
- hashChannel_ <- _sha256[:]
- token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
- _BA := strings.Split(token, ";")
- BA := _BA[len(_BA)-2]
- url := OvirtURL + "/ovirt-engine/api/vms"
- client := &http.Client{}
- req, err := http.NewRequest("GET", url, nil)
- if err != nil {
- fmt.Println(err)
- }
- req.Header.Add("Version", "4")
- req.Header.Add("Accept", "application/json")
- req.Header.Add("Authorization", BA)
- res, err := client.Do(req)
- if err != nil {
- fmt.Println(err)
- }
- defer res.Body.Close()
- body, err := ioutil.ReadAll(res.Body)
- if err != nil {
- fmt.Println(err)
- }
- //fmt.Printf("%s",body)
- //b, _ := json.MarshalIndent(body, "", " ")
- _VMLists := listVMs{}
- err = json.Unmarshal(body, &_VMLists)
- _listVMResponse := listVMResponse{
- Data: nil,
- Message: "Done",
- Origin: "ListVMs",
- Code: 1000,
- }
- _Data := _listVMResponse.Data
- y := struct {
- Fqdn string `json:"fqdn"`
- StartTime int64 `json:"start_time"`
- Status string `json:"status"`
- Name string `json:"name"`
- Description string `json:"description"`
- Comment string `json:"comment"`
- ID string `json:"id"`
- CPU struct {
- Topology struct {
- Cores string `json:"cores"`
- Sockets string `json:"sockets"`
- Threads string `json:"threads"`
- } `json:"topology"`
- } `json:"cpu"`
- Memory string `json:"memory"`
- CreationTime int64 `json:"creation_time"`
- Disk []struct {
- Name string `json:"Name"`
- TotalSize string `json:"TotalSize"`
- ActualSize string `json:"ActualSize"`
- } `json:"Disk"`
- NIC []struct {
- Mac string `json:"mac"`
- IPv4 string `json:"IPv4"`
- IPv6 string `json:"IPv6"`
- ReportedDevices struct {
- Mac string `json:"mac"`
- IPv4 string `json:"IPv4"`
- IPv6 string `json:"IPv6"`
- } `json:"reported_devices"`
- } `json:"NIC"`
- }{}
- //fmt.Println("Customer UUID:",login(BA).AuthenticatedUser.ID)
- for _, v := range _VMLists.VM {
- y.ID = v.ID
- y.Fqdn = v.Fqdn
- y.StartTime = v.StartTime
- y.Status = v.Status
- y.Name = v.Name
- if len(v.Name) > 35 {
- y.Name = v.Name[len(login(BA).AuthenticatedUser.ID)+3:]
- }
- y.Description = v.Description
- y.Comment = v.Comment
- y.CPU.Topology.Cores = v.CPU.Topology.Cores
- y.CPU.Topology.Sockets = v.CPU.Topology.Sockets
- y.CPU.Topology.Threads = v.CPU.Topology.Threads
- y.Memory = v.Memory
- y.CreationTime = v.CreationTime
- y.NIC = listNIC(v.ID, BA)
- y.Disk = listDisks(v.ID, BA)
- _Data = append(_Data, y)
- }
- _listVMResponse.Data = _Data
- if err != nil {
- //fmt.Println("Error on ListVM",err)
- //return CPUPrice, memPrice, StoragePrice, IPPrice, extraBWPrice
- resp := _response{
- Origin: "ovirt-listvms",
- Message: "Error in Parsing listVMs",
- Code: 1001,
- }
- return c.JSON(http.StatusInternalServerError, resp)
- }
- //fmt.Printf("%s", body)
- //b, _ := json.MarshalIndent(resp, "", " ")
- return c.JSON(http.StatusOK, _listVMResponse)
- //return c.String(http.StatusOK, string(b))
- }
- func (o ovirt) StartVM(c echo.Context) error {
- vmuuid := c.FormValue("VmUUID")
- user := c.Get("user").(*jwt.Token)
- claims := user.Claims.(jwt.MapClaims)
- _sha256 := sha256.Sum256([]byte(string(claims["name"].(string))))
- var hashChannel_ = make(chan []byte, 1)
- hashChannel_ <- _sha256[:]
- token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
- _BA := strings.Split(token, ";")
- BA := _BA[len(_BA)-2]
- url := OvirtURL + "/ovirt-engine/api/vms/" + vmuuid + "/start"
- method := "POST"
- __json := "{\"async\":\"true\"}"
- sha256 := sha256.Sum256([]byte(vmuuid))
- var hashChannel = make(chan []byte, 1)
- hashChannel <- sha256[:]
- ___json := encrypt(<-hashChannel, __json)
- startVM := addVMTask{
- URL: url,
- JSON: ___json,
- Method: method,
- Headers: nil,
- }
- startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Version", Value: "4"})
- startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Accept", Value: "application/json"})
- startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Content-Type", Value: "application/json"})
- startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Authorization", Value: BA})
- //req.Header.Add("Version", "4")
- //req.Header.Add("Accept", "application/json")
- //req.Header.Add("Authorization", BA)
- //req.Header.Add("Content-Type", "application/json")
- //
- //res, err := client.Do(req)
- //defer res.Body.Close()
- uuid, _ := uuidgen("APIGW-Ovirt")
- __startVM, _ := json.MarshalIndent(startVM, "", " ")
- //fmt.Println("StartVMHeaders: ", string(__startVMHeaders))
- addTask(uuid, string(__startVM), "", "APIGW", "VM Start", vmuuid, "1", "1")
- resp := _response{
- Origin: "ovirt-StartVM",
- Message: "Operation Started",
- Code: 1000,
- }
- //b, _ := json.MarshalIndent(resp, "", " ")
- return c.JSON(http.StatusOK, resp)
- //return c.String(http.StatusOK, string(b))
- }
- func (o ovirt) StopVM(c echo.Context) error {
- vmuuid := c.FormValue("VmUUID")
- user := c.Get("user").(*jwt.Token)
- claims := user.Claims.(jwt.MapClaims)
- _sha256 := sha256.Sum256([]byte(string(claims["name"].(string))))
- var hashChannel_ = make(chan []byte, 1)
- hashChannel_ <- _sha256[:]
- token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
- _BA := strings.Split(token, ";")
- BA := _BA[len(_BA)-2]
- {
- url := "https://ovirt-cl.zi-tel.com/ovirt-engine/api/vms/" + vmuuid + "/shutdown"
- method := "POST"
- payload := strings.NewReader(`{
- "async":"true"
- }`)
- client := &http.Client{}
- req, err := http.NewRequest(method, url, payload)
- if err != nil {
- fmt.Println(err)
- }
- req.Header.Add("Version", "4")
- req.Header.Add("Accept", "application/json")
- req.Header.Add("Authorization", BA)
- req.Header.Add("Content-Type", "application/json")
- res, err := client.Do(req)
- if err != nil {
- fmt.Println(err)
- }
- defer res.Body.Close()
- _, err = ioutil.ReadAll(res.Body)
- if err != nil {
- //return c.String(http.StatusBadRequest, "Error"+err.Error())
- return c.JSON(http.StatusBadRequest, "Error"+err.Error())
- }
- // fmt.Println(string(body))
- }
- resp := _response{
- Origin: "ovirt-StopVM",
- Message: "Operation Started",
- Code: 1000,
- }
- //b, _ := json.MarshalIndent(resp, "", " ")
- return c.JSON(http.StatusOK, resp)
- //return c.String(http.StatusOK, string(b))
- }
- func (o ovirt) RebootVM(c echo.Context) error {
- vmuuid := c.FormValue("VmUUID")
- user := c.Get("user").(*jwt.Token)
- claims := user.Claims.(jwt.MapClaims)
- _sha256 := sha256.Sum256([]byte(string(claims["name"].(string))))
- var hashChannel_ = make(chan []byte, 1)
- hashChannel_ <- _sha256[:]
- token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
- _BA := strings.Split(token, ";")
- BA := _BA[len(_BA)-2]
- {
- url := "https://ovirt-cl.zi-tel.com/ovirt-engine/api/vms/" + vmuuid + "/reboot"
- method := "POST"
- payload := strings.NewReader(`{
- "async":"true"
- }`)
- client := &http.Client{}
- req, err := http.NewRequest(method, url, payload)
- if err != nil {
- fmt.Println(err)
- }
- req.Header.Add("Version", "4")
- req.Header.Add("Accept", "application/json")
- req.Header.Add("Authorization", BA)
- req.Header.Add("Content-Type", "application/json")
- res, err := client.Do(req)
- if err != nil {
- fmt.Println(err)
- }
- defer res.Body.Close()
- _, err = ioutil.ReadAll(res.Body)
- if err != nil {
- //return c.String(http.StatusBadRequest, "Error"+err.Error())
- return c.JSON(http.StatusBadRequest, "Error"+err.Error())
- }
- }
- resp := _response{
- Origin: "ovirt-RebootVM",
- Message: "Operation Started",
- Code: 1000,
- }
- //b, _ := json.MarshalIndent(resp, "", " ")
- //return c.String(http.StatusOK, string(b))
- return c.JSON(http.StatusOK, resp)
- }
- func (o ovirt) PowerOffVM(c echo.Context) error {
- vmuuid := c.FormValue("VmUUID")
- user := c.Get("user").(*jwt.Token)
- claims := user.Claims.(jwt.MapClaims)
- _sha256 := sha256.Sum256([]byte(string(claims["name"].(string))))
- var hashChannel_ = make(chan []byte, 1)
- hashChannel_ <- _sha256[:]
- token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
- _BA := strings.Split(token, ";")
- BA := _BA[len(_BA)-2]
- {
- url := "https://ovirt-cl.zi-tel.com/ovirt-engine/api/vms/" + vmuuid + "/stop"
- method := "POST"
- payload := strings.NewReader(`{
- "async":"true"
- }`)
- client := &http.Client{}
- req, err := http.NewRequest(method, url, payload)
- if err != nil {
- fmt.Println(err)
- }
- req.Header.Add("Version", "4")
- req.Header.Add("Accept", "application/json")
- req.Header.Add("Authorization", BA)
- req.Header.Add("Content-Type", "application/json")
- res, err := client.Do(req)
- if err != nil {
- fmt.Println(err)
- }
- defer res.Body.Close()
- _, err = ioutil.ReadAll(res.Body)
- if err != nil {
- //return c.String(http.StatusBadRequest, "Error"+err.Error())
- return c.JSON(http.StatusBadRequest, "Error"+err.Error())
- }
- }
- resp := _response{
- Origin: "ovirt-RebootVM",
- Message: "Operation Started",
- Code: 1000,
- }
- //b, _ := json.MarshalIndent(resp, "", " ")
- //return c.String(http.StatusOK, string(b))
- return c.JSON(http.StatusOK, resp)
- }
- func (o ovirt) ResetVM(c echo.Context) error {
- vmuuid := c.FormValue("VmUUID")
- user := c.Get("user").(*jwt.Token)
- claims := user.Claims.(jwt.MapClaims)
- _sha256 := sha256.Sum256([]byte(string(claims["name"].(string))))
- var hashChannel_ = make(chan []byte, 1)
- hashChannel_ <- _sha256[:]
- token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
- _BA := strings.Split(token, ";")
- BA := _BA[len(_BA)-2]
- url := OvirtURL + "/ovirt-engine/api/vms/" + vmuuid + "/start"
- method := "POST"
- __json := "{\"async\":\"true\"}"
- sha256 := sha256.Sum256([]byte(vmuuid))
- var hashChannel = make(chan []byte, 1)
- hashChannel <- sha256[:]
- ___json := encrypt(<-hashChannel, __json)
- startVM := addVMTask{
- URL: url,
- JSON: ___json,
- Method: method,
- Headers: nil,
- }
- startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Version", Value: "4"})
- startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Accept", Value: "application/json"})
- startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Content-Type", Value: "application/json"})
- startVM.Headers = append(startVM.Headers, TaskHeader{Name: "Authorization", Value: BA})
- uuid, _ := uuidgen("APIGW-Ovirt")
- __startVM, _ := json.MarshalIndent(startVM, "", " ")
- addTask(uuid, string(__startVM), "", "APIGW", "VM Start", vmuuid, "1", "1")
- {
- url := "https://ovirt-cl.zi-tel.com/ovirt-engine/api/vms/" + vmuuid + "/stop"
- method := "POST"
- payload := strings.NewReader(`{
- "async":"true"
- }`)
- client := &http.Client{}
- req, err := http.NewRequest(method, url, payload)
- if err != nil {
- fmt.Println(err)
- }
- req.Header.Add("Version", "4")
- req.Header.Add("Accept", "application/json")
- req.Header.Add("Authorization", BA)
- req.Header.Add("Content-Type", "application/json")
- res, err := client.Do(req)
- if err != nil {
- fmt.Println(err)
- }
- defer res.Body.Close()
- _, err = ioutil.ReadAll(res.Body)
- if err != nil {
- //return c.String(http.StatusBadRequest, "Error"+err.Error())
- return c.JSON(http.StatusBadRequest, "Error"+err.Error())
- }
- }
- resp := _response{
- Origin: "ovirt-ResetVM",
- Message: "Operation Started",
- Code: 1000,
- }
- //b, _ := json.MarshalIndent(resp, "", " ")
- //return c.String(http.StatusOK, string(b))
- return c.JSON(http.StatusOK, resp)
- }
- func (o ovirt) AddNIC(c echo.Context) error {
- resp := _response{
- Origin: "ovirt-AddNIC",
- Message: "Done",
- Code: 1000,
- }
- //b, _ := json.MarshalIndent(resp, "", " ")
- //return c.String(http.StatusOK, string(b))
- return c.JSON(http.StatusOK, resp)
- }
- func (o ovirt) AddDisk(c echo.Context) error {
- resp := _response{
- Origin: "ovirt-AddDisk",
- Message: "Done",
- Code: 1000,
- }
- //b, _ := json.MarshalIndent(resp, "", " ")
- //return c.String(http.StatusOK, string(b))
- return c.JSON(http.StatusOK, resp)
- }
- func (o ovirt) EditVM(c echo.Context) error {
- resp := _response{
- Origin: "ovirt-EditVM",
- Message: "Done",
- Code: 1000,
- }
- //b, _ := json.MarshalIndent(resp, "", " ")
- //return c.String(http.StatusOK, string(b))
- return c.JSON(http.StatusOK, resp)
- }
- func (o ovirt) ResetPassword(c echo.Context) error {
- resp := _response{
- Origin: "ovirt-ResetPassword",
- Message: "not implemented",
- Code: 1003,
- }
- //b, _ := json.MarshalIndent(resp, "", " ")
- //return c.String(http.StatusOK, string(b))
- return c.JSON(http.StatusOK, resp)
- }
- func createVM(invoice_uuid string, apiJson string, uuid string) {
- type AddVMResponse struct {
- NextRunConfigurationExists string `json:"next_run_configuration_exists"`
- NumaTuneMode string `json:"numa_tune_mode"`
- Status string `json:"status"`
- StopTime int64 `json:"stop_time"`
- OriginalTemplate struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"original_template"`
- Template struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"template"`
- Actions struct {
- Link []struct {
- Href string `json:"href"`
- Rel string `json:"rel"`
- } `json:"link"`
- } `json:"actions"`
- Name string `json:"name"`
- Description string `json:"description"`
- Comment string `json:"comment"`
- Href string `json:"href"`
- ID string `json:"id"`
- Bios struct {
- BootMenu struct {
- Enabled string `json:"enabled"`
- } `json:"boot_menu"`
- Type string `json:"type"`
- } `json:"bios"`
- Console struct {
- Enabled string `json:"enabled"`
- } `json:"console"`
- CPU struct {
- Architecture string `json:"architecture"`
- Topology struct {
- Cores string `json:"cores"`
- Sockets string `json:"sockets"`
- Threads string `json:"threads"`
- } `json:"topology"`
- } `json:"cpu"`
- Display struct {
- AllowOverride string `json:"allow_override"`
- CopyPasteEnabled string `json:"copy_paste_enabled"`
- DisconnectAction string `json:"disconnect_action"`
- FileTransferEnabled string `json:"file_transfer_enabled"`
- Monitors string `json:"monitors"`
- SingleQxlPci string `json:"single_qxl_pci"`
- SmartcardEnabled string `json:"smartcard_enabled"`
- Type string `json:"type"`
- } `json:"display"`
- Initialization struct {
- AuthorizedSSHKeys string `json:"authorized_ssh_keys"`
- CloudInitNetworkProtocol string `json:"cloud_init_network_protocol"`
- CustomScript string `json:"custom_script"`
- HostName string `json:"host_name"`
- NicConfigurations struct {
- } `json:"nic_configurations"`
- RegenerateSSHKeys string `json:"regenerate_ssh_keys"`
- UserName string `json:"user_name"`
- } `json:"initialization"`
- Io struct {
- Threads string `json:"threads"`
- } `json:"io"`
- Memory string `json:"memory"`
- Migration struct {
- AutoConverge string `json:"auto_converge"`
- Compressed string `json:"compressed"`
- Encrypted string `json:"encrypted"`
- } `json:"migration"`
- Origin string `json:"origin"`
- Os struct {
- Boot struct {
- Devices struct {
- Device []string `json:"device"`
- } `json:"devices"`
- } `json:"boot"`
- Type string `json:"type"`
- } `json:"os"`
- Sso struct {
- Methods struct {
- Method []struct {
- ID string `json:"id"`
- } `json:"method"`
- } `json:"methods"`
- } `json:"sso"`
- Stateless string `json:"stateless"`
- Type string `json:"type"`
- Usb struct {
- Enabled string `json:"enabled"`
- } `json:"usb"`
- Cluster struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"cluster"`
- Quota struct {
- ID string `json:"id"`
- } `json:"quota"`
- CreationStatus string `json:"creation_status"`
- Link []struct {
- Href string `json:"href"`
- Rel string `json:"rel"`
- } `json:"link"`
- CPUShares string `json:"cpu_shares"`
- CreationTime int64 `json:"creation_time"`
- DeleteProtected string `json:"delete_protected"`
- HighAvailability struct {
- Enabled string `json:"enabled"`
- Priority string `json:"priority"`
- } `json:"high_availability"`
- LargeIcon struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"large_icon"`
- MemoryPolicy struct {
- Ballooning string `json:"ballooning"`
- Guaranteed string `json:"guaranteed"`
- Max string `json:"max"`
- } `json:"memory_policy"`
- MigrationDowntime string `json:"migration_downtime"`
- MultiQueuesEnabled string `json:"multi_queues_enabled"`
- RngDevice struct {
- Source string `json:"source"`
- } `json:"rng_device"`
- SmallIcon struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"small_icon"`
- SoundcardEnabled string `json:"soundcard_enabled"`
- StartPaused string `json:"start_paused"`
- StorageErrorResumeBehaviour string `json:"storage_error_resume_behaviour"`
- TimeZone struct {
- Name string `json:"name"`
- } `json:"time_zone"`
- VirtioScsi struct {
- Enabled string `json:"enabled"`
- } `json:"virtio_scsi"`
- CPUProfile struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"cpu_profile"`
- }
- _createVM := AddVMRequest{}
- //fmt.Println(apiJson)
- _err := json.Unmarshal([]byte(apiJson), &_createVM)
- if _err != nil {
- fmt.Println(apiJson)
- fmt.Println("Error in VMCreation step 1: ", _err.Error())
- }
- addvmresponse := AddVMResponse{}
- var body []byte
- {
- url := _createVM.URL
- method := _createVM.Method
- __json := _createVM.JSON
- client := &http.Client{}
- _json, _ := json.Marshal(__json)
- payload := strings.NewReader(string(_json))
- //payload := __json
- fmt.Println("First unmarshal", string(_json))
- fmt.Println("second unmarshal", __json.Description)
- req, err := http.NewRequest(method, url, payload)
- if err != nil {
- fmt.Println("Error in VMCreation step 2: ", err.Error())
- }
- _headers := _createVM.Headers
- for _, v := range _headers {
- req.Header.Add(v.Name, v.Value)
- }
- if err != nil {
- fmt.Println("Error in VMCreation step 3: ", err.Error())
- }
- res, err := client.Do(req)
- if err != nil {
- fmt.Println("Error in VMCreation step 3.5: ", err.Error())
- }
- defer res.Body.Close()
- body, _ = ioutil.ReadAll(res.Body)
- }
- //body := runAPICall(_createVM)
- err := json.Unmarshal(body, &addvmresponse)
- if err != nil {
- fmt.Println("Error in VMCreation step 4: ", err.Error())
- }
- toggleTask(uuid, 0)
- // find related VMInitialization Task
- //ruuid := ""
- {
- db, err := sql.Open("mysql", MySQLUSER+":"+MySQLPASS+"@tcp(127.0.0.1:3306)/zicloud")
- if err != nil {
- fmt.Println("Error in VMCreation step 3: ", _err.Error())
- }
- update2, err := db.Query("update service_profile set uuid='" + addvmresponse.ID + "' , modification_date=NOW() , active=1 where related_invoice='" + invoice_uuid + "'")
- update, err := db.Query("update scheduler set related_uuid='" + addvmresponse.ID + "' , active=1 where related_uuid='" + invoice_uuid + "' and type=1")
- defer update.Close()
- defer update2.Close()
- //toggleTask(ruuid, 1)
- }
- }
- func VMInitialization(relatedUuid string, apiCall string, uuid string) {
- iaas := &ovirt{}
- //fmt.Println("VM :", relatedUuid)
- status := iaas.vmStatus(relatedUuid)
- fmt.Println("VM :", relatedUuid, " is now: ", status)
- if status == "down" || status == "suspended" {
- //fmt.Println("APICall: ", apiCall)
- startVM := addVMTask{}
- //b, _ := json.Marshal(apiCall)
- _err := json.Unmarshal([]byte(apiCall), &startVM)
- if _err != nil {
- fmt.Println("Error in VMInitialization: ", _err.Error())
- }
- //fmt.Println("calling initialization for VM :", relatedUuid)
- words := strings.Split(startVM.URL, "/")
- //fmt.Println("Invoice : ", words[6])
- _sha256 := sha256.Sum256([]byte(words[6]))
- var hashChannel_ = make(chan []byte, 1)
- hashChannel_ <- _sha256[:]
- //fmt.Println(" startVM.JSON: ", startVM.JSON)
- startVM.JSON = decrypt(<-hashChannel_, startVM.JSON)
- //fmt.Println("decrypted json: ",startVM.JSON)
- startVM.URL = OvirtURL + "/ovirt-engine/api/vms/" + relatedUuid + "/start"
- //fmt.Println("Start URL: ", startVM.URL)
- //fmt.Println("Initialize JSON: ", decrypt(<-hashChannel_, startVM.JSON))
- runAPICall(startVM)
- toggleTask(uuid, 0)
- }
- }
- func vmStatistics(BA string, VMUUID string) (string, float64, float64, error) {
- //ram,cpu,storage
- var _disk []string
- {
- type DiskAttachments struct {
- DiskAttachment []struct {
- Active string `json:"active"`
- Bootable string `json:"bootable"`
- Interface string `json:"interface"`
- LogicalName string `json:"logical_name"`
- PassDiscard string `json:"pass_discard"`
- ReadOnly string `json:"read_only"`
- UsesScsiReservation string `json:"uses_scsi_reservation"`
- Disk struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"disk"`
- VM struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"vm"`
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"disk_attachment"`
- }
- url := OvirtURL + "/ovirt-engine/api/vms/" + VMUUID + "/diskattachments"
- //fmt.Println("Url:" ,url)
- method := "GET"
- client := &http.Client{}
- req, err := http.NewRequest(method, url, nil)
- if err != nil {
- return "", -1, -1, errors.New("unexpected Error")
- }
- req.Header.Add("Version", "4")
- req.Header.Add("Accept", "application/json")
- req.Header.Add("Authorization", BA)
- res, err := client.Do(req)
- body, err := ioutil.ReadAll(res.Body)
- defer res.Body.Close()
- diskattachments := DiskAttachments{}
- _err := json.Unmarshal(body, &diskattachments)
- if _err != nil {
- fmt.Println("Error in vmStatistics 1: ", _err)
- }
- for _, v := range diskattachments.DiskAttachment {
- url := OvirtURL + "/ovirt-engine/api/disks/" + v.Disk.ID
- type DiskAttachment struct {
- ActualSize string `json:"actual_size"`
- Alias string `json:"alias"`
- Backup string `json:"backup"`
- ContentType string `json:"content_type"`
- Format string `json:"format"`
- ImageID string `json:"image_id"`
- PropagateErrors string `json:"propagate_errors"`
- ProvisionedSize string `json:"provisioned_size"`
- QcowVersion string `json:"qcow_version"`
- Shareable string `json:"shareable"`
- Sparse string `json:"sparse"`
- Status string `json:"status"`
- StorageType string `json:"storage_type"`
- TotalSize string `json:"total_size"`
- WipeAfterDelete string `json:"wipe_after_delete"`
- DiskProfile struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"disk_profile"`
- Quota struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"quota"`
- StorageDomains struct {
- StorageDomain []struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"storage_domain"`
- } `json:"storage_domains"`
- Actions struct {
- Link []struct {
- Href string `json:"href"`
- Rel string `json:"rel"`
- } `json:"link"`
- } `json:"actions"`
- Name string `json:"name"`
- Description string `json:"description"`
- Href string `json:"href"`
- ID string `json:"id"`
- Link []struct {
- Href string `json:"href"`
- Rel string `json:"rel"`
- } `json:"link"`
- }
- //fmt.Println("Url:" ,url)
- method := "GET"
- client := &http.Client{}
- req, _ := http.NewRequest(method, url, nil)
- //if err != nil {
- // return "Null"
- //}
- req.Header.Add("Version", "4")
- req.Header.Add("Accept", "application/json")
- req.Header.Add("Authorization", BA)
- res, _ := client.Do(req)
- body, _ := ioutil.ReadAll(res.Body)
- //fmt.Println("full response: ",string(body))
- disk := DiskAttachment{}
- _err := json.Unmarshal(body, &disk)
- if _err != nil {
- fmt.Println("Error in vmStatistics 2 : ", _err)
- }
- defer res.Body.Close()
- _disk = append(_disk, disk.ProvisionedSize)
- //_disk = D_disk + "" + disk.ProvisionedSize+" "
- }
- }
- url := OvirtURL + "/ovirt-engine/api/vms/" + VMUUID + "/statistics"
- //fmt.Println("Url:" ,url)
- method := "GET"
- client := &http.Client{}
- req, err := http.NewRequest(method, url, nil)
- if err != nil {
- return "", -1, -1, errors.New("unexpected Error")
- }
- req.Header.Add("Version", "4")
- req.Header.Add("Accept", "application/json")
- req.Header.Add("Authorization", BA)
- res, err := client.Do(req)
- body, err := ioutil.ReadAll(res.Body)
- fmt.Println("Code: ", res.StatusCode)
- if err != nil || res.StatusCode == 404 {
- return "", -1, -1, errors.New("unexpected Error")
- }
- defer res.Body.Close()
- //fmt.Println("full response: ", string(body))
- _vmstatistics := VMStatistics{}
- _err := json.Unmarshal(body, &_vmstatistics)
- if _err != nil {
- fmt.Println("Error in vmStatistics 3: ", _err)
- }
- cpuUUID := _vmstatistics.Statistic[4].ID
- memUsedUUID := _vmstatistics.Statistic[1].ID
- memTotalUUID := _vmstatistics.Statistic[0].ID
- //fmt.Println(memUsedUUID)
- var cpu, memUsed, memTotal string
- type ItemUsage struct {
- Kind string `json:"kind"`
- Type string `json:"type"`
- Unit string `json:"unit"`
- Values struct {
- Value []struct {
- Datum float64 `json:"datum"`
- } `json:"value"`
- } `json:"values"`
- VM struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"vm"`
- Name string `json:"name"`
- Description string `json:"description"`
- Href string `json:"href"`
- ID string `json:"id"`
- }
- {
- url := OvirtURL + "/ovirt-engine/api/vms/" + VMUUID + "/statistics/" + cpuUUID
- //fmt.Println("Url:" ,url)
- method := "GET"
- client := &http.Client{}
- req, err := http.NewRequest(method, url, nil)
- if err != nil {
- return "", -1, -1, errors.New("unexpected Error")
- }
- req.Header.Add("Version", "4")
- req.Header.Add("Accept", "application/json")
- req.Header.Add("Authorization", BA)
- res, err := client.Do(req)
- defer res.Body.Close()
- body, err := ioutil.ReadAll(res.Body)
- cpuUsage := ItemUsage{}
- _err := json.Unmarshal(body, &cpuUsage)
- if _err != nil {
- fmt.Println("Error in vmStatistics 4 ", _err)
- }
- cpu = fmt.Sprintf("%f", cpuUsage.Values.Value[0].Datum)
- }
- {
- url := OvirtURL + "/ovirt-engine/api/vms/" + VMUUID + "/statistics/" + memUsedUUID
- //fmt.Println("Url:" ,url)
- method := "GET"
- client := &http.Client{}
- req, err := http.NewRequest(method, url, nil)
- if err != nil {
- return "", -1, -1, errors.New("unexpected Error")
- }
- req.Header.Add("Version", "4")
- req.Header.Add("Accept", "application/json")
- req.Header.Add("Authorization", BA)
- res, err := client.Do(req)
- defer res.Body.Close()
- body, err := ioutil.ReadAll(res.Body)
- memUsage := ItemUsage{}
- _err := json.Unmarshal(body, &memUsage)
- if _err != nil {
- fmt.Println("Error in vmStatistics 5: ", _err)
- }
- memUsed = fmt.Sprintf("%f", memUsage.Values.Value[0].Datum)
- }
- {
- url := OvirtURL + "/ovirt-engine/api/vms/" + VMUUID + "/statistics/" + memTotalUUID
- //fmt.Println("Url:" ,url)
- method := "GET"
- client := &http.Client{}
- req, err := http.NewRequest(method, url, nil)
- if err != nil {
- return "", -1, -1, errors.New("unexpected Error")
- }
- req.Header.Add("Version", "4")
- req.Header.Add("Accept", "application/json")
- req.Header.Add("Authorization", BA)
- res, err := client.Do(req)
- defer res.Body.Close()
- body, err := ioutil.ReadAll(res.Body)
- memUsage := ItemUsage{}
- _err := json.Unmarshal(body, &memUsage)
- if _err != nil {
- fmt.Println("Error in vmStatistics 6: ", _err)
- }
- memTotal = fmt.Sprintf("%f", memUsage.Values.Value[0].Datum)
- }
- //fmt.Println("CPU:" ,cpu)
- //fmt.Println("MEM:", memUsed)
- //fmt.Println("MEM:", memTotal)
- _memusage, _ := strconv.ParseFloat(memUsed, 32)
- _memtotal, _ := strconv.ParseFloat(memTotal, 32)
- mem := _memusage / _memtotal
- _cpu, _ := strconv.ParseFloat(cpu, 64)
- return strings.Join(_disk, ", "), _cpu, mem, nil
- }
- func (o ovirt) vmDetails(c echo.Context) error {
- //name,...,traffic,ip,status
- user := c.Get("user").(*jwt.Token)
- claims := user.Claims.(jwt.MapClaims)
- _sha256 := sha256.Sum256([]byte(string(claims["name"].(string))))
- var hashChannel_ = make(chan []byte, 1)
- hashChannel_ <- _sha256[:]
- token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
- _BA := strings.Split(token, ";")
- BA := _BA[len(_BA)-2]
- uuid := c.FormValue("uuid")
- if len(uuid) < 5 {
- resp := _response{
- Origin: "vmDetails",
- Message: "Missing UUID",
- Code: 1001,
- }
- return c.JSON(http.StatusNotFound, resp)
- }
- type vmStatus struct {
- NextRunConfigurationExists string `json:"next_run_configuration_exists"`
- NumaTuneMode string `json:"numa_tune_mode"`
- Status string `json:"status"`
- StopTime int64 `json:"stop_time"`
- OriginalTemplate struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"original_template"`
- Template struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"template"`
- Actions struct {
- Link []struct {
- Href string `json:"href"`
- Rel string `json:"rel"`
- } `json:"link"`
- } `json:"actions"`
- Name string `json:"name"`
- Description string `json:"description"`
- Comment string `json:"comment"`
- Href string `json:"href"`
- ID string `json:"id"`
- Bios struct {
- BootMenu struct {
- Enabled string `json:"enabled"`
- } `json:"boot_menu"`
- Type string `json:"type"`
- } `json:"bios"`
- CPU struct {
- Architecture string `json:"architecture"`
- Topology struct {
- Cores string `json:"cores"`
- Sockets string `json:"sockets"`
- Threads string `json:"threads"`
- } `json:"topology"`
- } `json:"cpu"`
- Display struct {
- AllowOverride string `json:"allow_override"`
- CopyPasteEnabled string `json:"copy_paste_enabled"`
- DisconnectAction string `json:"disconnect_action"`
- FileTransferEnabled string `json:"file_transfer_enabled"`
- Monitors string `json:"monitors"`
- SingleQxlPci string `json:"single_qxl_pci"`
- SmartcardEnabled string `json:"smartcard_enabled"`
- Type string `json:"type"`
- } `json:"display"`
- Initialization struct {
- AuthorizedSSHKeys string `json:"authorized_ssh_keys"`
- CloudInitNetworkProtocol string `json:"cloud_init_network_protocol"`
- CustomScript string `json:"custom_script"`
- HostName string `json:"host_name"`
- NicConfigurations struct {
- } `json:"nic_configurations"`
- RegenerateSSHKeys string `json:"regenerate_ssh_keys"`
- UserName string `json:"user_name"`
- } `json:"initialization"`
- Io struct {
- Threads string `json:"threads"`
- } `json:"io"`
- Memory string `json:"memory"`
- Migration struct {
- AutoConverge string `json:"auto_converge"`
- Compressed string `json:"compressed"`
- Encrypted string `json:"encrypted"`
- } `json:"migration"`
- Origin string `json:"origin"`
- Os struct {
- Boot struct {
- Devices struct {
- Device []string `json:"device"`
- } `json:"devices"`
- } `json:"boot"`
- Type string `json:"type"`
- } `json:"os"`
- Sso struct {
- Methods struct {
- Method []struct {
- ID string `json:"id"`
- } `json:"method"`
- } `json:"methods"`
- } `json:"sso"`
- Stateless string `json:"stateless"`
- Type string `json:"type"`
- Usb struct {
- Enabled string `json:"enabled"`
- } `json:"usb"`
- Cluster struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"cluster"`
- Quota struct {
- ID string `json:"id"`
- } `json:"quota"`
- Link []struct {
- Href string `json:"href"`
- Rel string `json:"rel"`
- } `json:"link"`
- CPUShares string `json:"cpu_shares"`
- CreationTime int64 `json:"creation_time"`
- DeleteProtected string `json:"delete_protected"`
- HighAvailability struct {
- Enabled string `json:"enabled"`
- Priority string `json:"priority"`
- } `json:"high_availability"`
- LargeIcon struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"large_icon"`
- MemoryPolicy struct {
- Ballooning string `json:"ballooning"`
- Guaranteed string `json:"guaranteed"`
- Max string `json:"max"`
- } `json:"memory_policy"`
- MigrationDowntime string `json:"migration_downtime"`
- MultiQueuesEnabled string `json:"multi_queues_enabled"`
- PlacementPolicy struct {
- Affinity string `json:"affinity"`
- Hosts struct {
- Host []struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"host"`
- } `json:"hosts"`
- } `json:"placement_policy"`
- SmallIcon struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"small_icon"`
- StartPaused string `json:"start_paused"`
- StorageErrorResumeBehaviour string `json:"storage_error_resume_behaviour"`
- TimeZone struct {
- Name string `json:"name"`
- } `json:"time_zone"`
- CPUProfile struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"cpu_profile"`
- }
- //url := "https://ovirt-cl.zi-tel.com/ovirt-engine/api/vms/c1a44128-6c6c-406b-99d8-4a68a99380c9"
- url := OvirtURL + "/ovirt-engine/api/vms/" + uuid
- //fmt.Println("Url:" ,url)
- method := "GET"
- client := &http.Client{}
- req, _ := http.NewRequest(method, url, nil)
- //if err != nil {
- // return "Null"
- //}
- req.Header.Add("Version", "4")
- req.Header.Add("Accept", "application/json")
- req.Header.Add("Authorization", BA)
- res, _ := client.Do(req)
- body, _ := ioutil.ReadAll(res.Body)
- //fmt.Println("full response: ",string(body))
- _vmstatus := vmStatus{}
- _err := json.Unmarshal(body, &_vmstatus)
- if _err != nil {
- resp := _response{
- Origin: "vmDetails",
- Message: "Not Found",
- Code: 1001,
- }
- return c.JSON(http.StatusNotFound, resp)
- }
- defer res.Body.Close()
- // disk, cpu, ram, err := vmStatistics(BA, uuid)
- cpuCore, _ := strconv.Atoi(_vmstatus.CPU.Topology.Cores)
- cpuThread, _ := strconv.Atoi(_vmstatus.CPU.Topology.Threads)
- cpuSocket, _ := strconv.Atoi(_vmstatus.CPU.Topology.Sockets)
- cpu := cpuThread * cpuCore * cpuSocket
- ram, _ := strconv.Atoi(_vmstatus.Memory)
- diskStruct := listDisks(uuid, BA)
- disk := 0
- _size := 0
- for _, v := range diskStruct {
- _size, _ = strconv.Atoi(v.TotalSize)
- }
- disk += _size
- nicStruct := listNIC(uuid, BA)
- nic := len(nicStruct)
- type JSONDetails struct {
- Name string `json:"name"`
- Value string `json:"value"`
- Type string `json:"type"`
- }
- vmJsonDetails := [8]JSONDetails{}
- {
- db, err := sql.Open("mysql", MySQLUSER+":"+MySQLPASS+"@tcp(127.0.0.1:3306)/zicloud")
- if err != nil {
- resp := _response{
- Origin: "vmDetails",
- Message: "Not Found",
- Code: 1001,
- }
- return c.JSON(http.StatusNotFound, resp)
- }
- defer db.Close()
- results, err := db.Query("select details from service_profile where uuid='" + uuid + "'")
- //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")
- detailsStr := ""
- for results.Next() {
- _ = results.Scan(&detailsStr)
- }
- json.Unmarshal([]byte(detailsStr), &vmJsonDetails)
- }
- type AutoGenerated struct {
- Message struct {
- Disk string `json:"Disk"`
- Memory string `json:"Memory"`
- CPU string `json:"CPU"`
- NIC string `json:"NIC"`
- Traffic string `json:"Traffic"`
- Status string `json:"Status"`
- Name string `json:"Name"`
- Template string `json:"Template"`
- } `json:"message"`
- Origin string `json:"origin"`
- Code int `json:"code"`
- }
- resp := AutoGenerated{
- Message: struct {
- Disk string `json:"Disk"`
- Memory string `json:"Memory"`
- CPU string `json:"CPU"`
- NIC string `json:"NIC"`
- Traffic string `json:"Traffic"`
- Status string `json:"Status"`
- Name string `json:"Name"`
- Template string `json:"Template"`
- }{
- Disk: fmt.Sprintf("%d", disk),
- Memory: fmt.Sprintf("%d", ram),
- CPU: fmt.Sprintf("%d", cpu),
- NIC: fmt.Sprintf("%d", nic),
- Traffic: vmJsonDetails[5].Value,
- Status: _vmstatus.Status,
- // v.Name[len(login(BA).AuthenticatedUser.ID)+3:]
- Name: _vmstatus.Name[len(login(BA).AuthenticatedUser.ID)+3:],
- Template: vmJsonDetails[7].Value,
- },
- Origin: "vmDetails",
- Code: 1000,
- }
- return c.JSON(http.StatusOK, resp)
- //return _vmstatus.Status, _vmstatus.Name, disk, cpu, ram
- }
- func (o ovirt) ovirtPayment(c echo.Context) error {
- invoiceUuid := c.FormValue("invoiceUuid")
- db, err := sql.Open("mysql", MySQLUSER+":"+MySQLPASS+"@tcp(127.0.0.1:3306)/zicloud")
- //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")
- ///TODO: check duplicate payment confirmation by Invoice table
- if err != nil {
- }
- update, err := db.Query("update scheduler set active='1' where related_uuid='" + invoiceUuid + "' and type=0")
- defer db.Close()
- if err != nil {
- }
- defer update.Close()
- resp := _response{
- Origin: "ovirt-ovirtPayment",
- Message: "Done",
- Code: 1000,
- }
- //b, _ := json.MarshalIndent(resp, "", " ")
- //return c.String(http.StatusOK, string(b))
- return c.JSON(http.StatusOK, resp)
- }
- func listNIC(VMUUID string, BA string) []struct {
- Mac string `json:"mac"`
- IPv4 string `json:"IPv4"`
- IPv6 string `json:"IPv6"`
- ReportedDevices struct {
- Mac string `json:"mac"`
- IPv4 string `json:"IPv4"`
- IPv6 string `json:"IPv6"`
- } `json:"reported_devices"`
- } {
- type NICList struct {
- NIC []struct {
- Mac string `json:"mac"`
- IPv4 string `json:"IPv4"`
- IPv6 string `json:"IPv6"`
- ReportedDevices struct {
- Mac string `json:"mac"`
- IPv4 string `json:"IPv4"`
- IPv6 string `json:"IPv6"`
- } `json:"reported_devices"`
- } `json:"NIC"`
- }
- type VMNIC struct {
- Nic []struct {
- Interface string `json:"interface"`
- Linked string `json:"linked"`
- Mac struct {
- Address string `json:"address"`
- } `json:"mac"`
- Plugged string `json:"plugged"`
- ReportedDevices struct {
- ReportedDevice []struct {
- Ips struct {
- IP []struct {
- Address string `json:"address"`
- Version string `json:"version"`
- } `json:"ip"`
- } `json:"ips"`
- Mac struct {
- Address string `json:"address"`
- } `json:"mac"`
- Type string `json:"type"`
- Name string `json:"name"`
- Description string `json:"description"`
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"reported_device"`
- } `json:"reported_devices"`
- VnicProfile struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"vnic_profile"`
- Actions struct {
- Link []struct {
- Href string `json:"href"`
- Rel string `json:"rel"`
- } `json:"link"`
- } `json:"actions"`
- Name string `json:"name"`
- Href string `json:"href"`
- ID string `json:"id"`
- VM struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"vm"`
- Link []struct {
- Href string `json:"href"`
- Rel string `json:"rel"`
- } `json:"link"`
- } `json:"nic"`
- }
- url := "https://ovirt-cl.zi-tel.com/ovirt-engine/api/vms/" + VMUUID + "/nics"
- method := "GET"
- payload := strings.NewReader(``)
- client := &http.Client{}
- req, err := http.NewRequest(method, url, payload)
- if err != nil {
- //fmt.Println(err)
- return nil
- }
- req.Header.Add("Version", "4")
- req.Header.Add("Accept", "application/json")
- req.Header.Add("Authorization", BA)
- res, err := client.Do(req)
- if err != nil {
- //fmt.Println(err)
- ///TODO: ErrorHandling
- return nil
- }
- defer res.Body.Close()
- body, err := ioutil.ReadAll(res.Body)
- if err != nil {
- //fmt.Println(err)
- ///TODO: ErrorHandling
- return nil
- }
- _VMNIC := VMNIC{}
- err = json.Unmarshal(body, &_VMNIC)
- //fmt.Println("ListNIC: res", string(body))
- if err != nil {
- ///TODO: ErrorHandling
- //fmt.Println(err)
- //return CPUPrice, memPrice, StoragePrice, IPPrice, extraBWPrice
- }
- _NICList := NICList{}
- _Data := _NICList.NIC
- x := struct {
- Mac string `json:"mac"`
- IPv4 string `json:"IPv4"`
- IPv6 string `json:"IPv6"`
- ReportedDevices struct {
- Mac string `json:"mac"`
- IPv4 string `json:"IPv4"`
- IPv6 string `json:"IPv6"`
- } `json:"reported_devices"`
- }{}
- for _, i := range _VMNIC.Nic {
- x.IPv4 = "1.1.1.1"
- ///TODO:GetAssignedIP from DHCP Table and remove this block
- x.IPv6 = "Null"
- x.Mac = i.Mac.Address
- if len(i.ReportedDevices.ReportedDevice) > 0 {
- x.ReportedDevices.Mac = i.ReportedDevices.ReportedDevice[0].Mac.Address
- if len(i.ReportedDevices.ReportedDevice[0].Ips.IP) > 1 {
- x.ReportedDevices.IPv4 = i.ReportedDevices.ReportedDevice[0].Ips.IP[0].Address
- x.ReportedDevices.IPv6 = i.ReportedDevices.ReportedDevice[0].Ips.IP[1].Address
- }
- } else {
- x.ReportedDevices.Mac = ""
- x.ReportedDevices.IPv4 = ""
- x.ReportedDevices.IPv6 = ""
- }
- _Data = append(_Data, x)
- }
- _NICList.NIC = _Data
- return _NICList.NIC
- }
- func listDisks(VMUUID string, ba string) []struct {
- Name string `json:"Name"`
- TotalSize string `json:"TotalSize"`
- ActualSize string `json:"ActualSize"`
- } {
- type DiskList struct {
- Disk []struct {
- Name string `json:"Name"`
- TotalSize string `json:"TotalSize"`
- ActualSize string `json:"ActualSize"`
- } `json:"Disk"`
- }
- type ListDisks struct {
- DiskAttachment []struct {
- Active string `json:"active"`
- Bootable string `json:"bootable"`
- Interface string `json:"interface"`
- LogicalName string `json:"logical_name"`
- PassDiscard string `json:"pass_discard"`
- ReadOnly string `json:"read_only"`
- UsesScsiReservation string `json:"uses_scsi_reservation"`
- Disk struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"disk"`
- VM struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"vm"`
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"disk_attachment"`
- }
- url := "https://ovirt-cl.zi-tel.com/ovirt-engine/api/vms/" + VMUUID + "/diskattachments"
- method := "GET"
- payload := strings.NewReader(``)
- client := &http.Client{}
- req, err := http.NewRequest(method, url, payload)
- if err != nil {
- //fmt.Println(err)
- return nil
- }
- req.Header.Add("Version", "4")
- req.Header.Add("Accept", "application/json")
- req.Header.Add("Authorization", ba)
- res, err := client.Do(req)
- if err != nil {
- //fmt.Println(err)
- return nil
- }
- defer res.Body.Close()
- body, err := ioutil.ReadAll(res.Body)
- //fmt.Println("ListDisk: res", string(body))
- if err != nil {
- //fmt.Println(err)
- return nil
- }
- _ListDisks := ListDisks{}
- err = json.Unmarshal(body, &_ListDisks)
- if err != nil {
- //fmt.Println(err)
- return nil
- }
- _DiskList := DiskList{}
- for _, v := range _ListDisks.DiskAttachment {
- _DiskList.Disk = append(_DiskList.Disk, DiskDetails(v.Disk.ID, ba))
- }
- return _DiskList.Disk
- }
- func DiskDetails(id string, ba string) struct {
- Name string `json:"Name"`
- TotalSize string `json:"TotalSize"`
- ActualSize string `json:"ActualSize"`
- } {
- type DiskDetail struct {
- ActualSize string `json:"actual_size"`
- Alias string `json:"alias"`
- Backup string `json:"backup"`
- ContentType string `json:"content_type"`
- Format string `json:"format"`
- ImageID string `json:"image_id"`
- PropagateErrors string `json:"propagate_errors"`
- ProvisionedSize string `json:"provisioned_size"`
- QcowVersion string `json:"qcow_version"`
- Shareable string `json:"shareable"`
- Sparse string `json:"sparse"`
- Status string `json:"status"`
- StorageType string `json:"storage_type"`
- TotalSize string `json:"total_size"`
- WipeAfterDelete string `json:"wipe_after_delete"`
- DiskProfile struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"disk_profile"`
- Quota struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"quota"`
- StorageDomains struct {
- StorageDomain []struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"storage_domain"`
- } `json:"storage_domains"`
- Actions struct {
- Link []struct {
- Href string `json:"href"`
- Rel string `json:"rel"`
- } `json:"link"`
- } `json:"actions"`
- Name string `json:"name"`
- Description string `json:"description"`
- Href string `json:"href"`
- ID string `json:"id"`
- Link []struct {
- Href string `json:"href"`
- Rel string `json:"rel"`
- } `json:"link"`
- }
- //fmt.Println("List Disk: ",id)
- url := "https://ovirt-cl.zi-tel.com/ovirt-engine/api/disks/" + id
- method := "GET"
- payload := strings.NewReader(``)
- client := &http.Client{}
- req, err := http.NewRequest(method, url, payload)
- if err != nil {
- //fmt.Println(err)
- }
- req.Header.Add("Version", "4")
- req.Header.Add("Accept", "application/json")
- req.Header.Add("Authorization", ba)
- res, err := client.Do(req)
- if err != nil {
- //fmt.Println(err)
- }
- defer res.Body.Close()
- body, err := ioutil.ReadAll(res.Body)
- if err != nil {
- //fmt.Println(err)
- }
- _DiskDetail := DiskDetail{}
- err = json.Unmarshal(body, &_DiskDetail)
- if err != nil {
- //fmt.Println(err)
- }
- Disk := struct {
- Name string `json:"Name"`
- TotalSize string `json:"TotalSize"`
- ActualSize string `json:"ActualSize"`
- }{
- Name: _DiskDetail.Alias,
- TotalSize: _DiskDetail.ProvisionedSize,
- ActualSize: _DiskDetail.ActualSize,
- }
- return Disk
- }
- func (o ovirt) VNC(c echo.Context) error {
- type graphicConsoleList struct {
- GraphicsConsole []struct {
- Protocol string `json:"protocol"`
- VM struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"vm"`
- Actions struct {
- Link []struct {
- Href string `json:"href"`
- Rel string `json:"rel"`
- } `json:"link"`
- } `json:"actions"`
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"graphics_console"`
- }
- type vnc struct {
- RemoteViewerConnectionFile string `json:"remote_viewer_connection_file"`
- }
- user := c.Get("user").(*jwt.Token)
- claims := user.Claims.(jwt.MapClaims)
- _sha256 := sha256.Sum256([]byte(string(claims["name"].(string))))
- var hashChannel_ = make(chan []byte, 1)
- hashChannel_ <- _sha256[:]
- token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
- _BA := strings.Split(token, ";")
- BA := _BA[len(_BA)-2]
- vmuuid := c.FormValue("VmUUID")
- urlgraphiclist := OvirtURL + "/ovirt-engine/api/vms/" + vmuuid + "/graphicsconsoles"
- client := &http.Client{}
- req, err := http.NewRequest("Get", urlgraphiclist, nil)
- if err != nil {
- fmt.Println(err)
- }
- req.Header.Add("Version", "4")
- req.Header.Add("Accept", "application/json")
- req.Header.Add("Authorization", BA)
- res, err := client.Do(req)
- body, err := ioutil.ReadAll(res.Body)
- defer res.Body.Close()
- _graphicConsoleList := graphicConsoleList{}
- err = json.Unmarshal(body, &_graphicConsoleList)
- urlvncfile := OvirtURL + "/ovirt-engine/api/vms/" + vmuuid + "/graphicsconsoles/" + _graphicConsoleList.GraphicsConsole[0].ID + "/remoteviewerconnectionfile"
- client2 := &http.Client{}
- payload := strings.NewReader(`{
- }`)
- req2, err := http.NewRequest("POST", urlvncfile, payload)
- req2.Header.Add("Version", "4")
- req2.Header.Add("Accept", "application/json")
- req2.Header.Add("Content-Type", "application/json")
- req2.Header.Add("Authorization", BA)
- res2, err := client2.Do(req2)
- body2, err := ioutil.ReadAll(res2.Body)
- _vnc := vnc{}
- err = json.Unmarshal(body2, &_vnc)
- defer res2.Body.Close()
- result := _vnc.RemoteViewerConnectionFile
- dhost := strings.Split(result, "\n")[2]
- dport := strings.Split(result, "\n")[3]
- password := strings.Split(result, "\n")[4]
- mrand.Seed(time.Now().UTC().UnixNano())
- randInt := func(min, max int) int {
- return min + mrand.Intn(max-min)
- }
- lport := randInt(5800, 6000)
- {
- app := "/root/novncRunner"
- arg0 := fmt.Sprintf("%d", lport)
- arg1 := strings.Split(dhost, "=")
- arg2 := strings.Split(dport, "=")
- exec.Command(app, arg2[1], arg1[1], arg0).Output()
- }
- resp := _response{
- Origin: "ovirt-VNC",
- Message: "http://zi-cloud.ir:" + fmt.Sprintf("%d", lport) + "/vnc.html?autoconnect=true&password=" + strings.Split(password, "=")[1],
- Code: 1000,
- }
- return c.JSON(http.StatusOK, resp)
- }
- func (o ovirt) listTemplate(c echo.Context) error {
- type templateList struct {
- Template []struct {
- Status string `json:"status"`
- Version struct {
- VersionName string `json:"version_name"`
- VersionNumber string `json:"version_number"`
- BaseTemplate struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"base_template"`
- } `json:"version"`
- Actions struct {
- Link []struct {
- Href string `json:"href"`
- Rel string `json:"rel"`
- } `json:"link"`
- } `json:"actions"`
- Name string `json:"name"`
- Description string `json:"description"`
- Comment string `json:"comment"`
- Href string `json:"href"`
- ID string `json:"id"`
- Bios struct {
- BootMenu struct {
- Enabled string `json:"enabled"`
- } `json:"boot_menu"`
- Type string `json:"type"`
- } `json:"bios"`
- CPU struct {
- Architecture string `json:"architecture"`
- Topology struct {
- Cores string `json:"cores"`
- Sockets string `json:"sockets"`
- Threads string `json:"threads"`
- } `json:"topology"`
- } `json:"cpu"`
- Display struct {
- AllowOverride string `json:"allow_override"`
- CopyPasteEnabled string `json:"copy_paste_enabled"`
- DisconnectAction string `json:"disconnect_action"`
- FileTransferEnabled string `json:"file_transfer_enabled"`
- Monitors string `json:"monitors"`
- SingleQxlPci string `json:"single_qxl_pci"`
- SmartcardEnabled string `json:"smartcard_enabled"`
- Type string `json:"type"`
- } `json:"display"`
- Io struct {
- Threads string `json:"threads"`
- } `json:"io"`
- Memory string `json:"memory"`
- Migration struct {
- AutoConverge string `json:"auto_converge"`
- Compressed string `json:"compressed"`
- Encrypted string `json:"encrypted"`
- } `json:"migration"`
- Origin string `json:"origin"`
- Os struct {
- Boot struct {
- Devices struct {
- Device []string `json:"device"`
- } `json:"devices"`
- } `json:"boot"`
- Type string `json:"type"`
- } `json:"os"`
- Sso struct {
- Methods struct {
- Method []struct {
- ID string `json:"id"`
- } `json:"method"`
- } `json:"methods"`
- } `json:"sso"`
- Stateless string `json:"stateless"`
- Type string `json:"type"`
- Usb struct {
- Enabled string `json:"enabled"`
- } `json:"usb"`
- Link []struct {
- Href string `json:"href"`
- Rel string `json:"rel"`
- } `json:"link"`
- CPUShares string `json:"cpu_shares"`
- CreationTime int64 `json:"creation_time"`
- DeleteProtected string `json:"delete_protected"`
- HighAvailability struct {
- Enabled string `json:"enabled"`
- Priority string `json:"priority"`
- } `json:"high_availability"`
- LargeIcon struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"large_icon"`
- MemoryPolicy struct {
- Guaranteed string `json:"guaranteed"`
- Max string `json:"max"`
- } `json:"memory_policy"`
- MigrationDowntime string `json:"migration_downtime"`
- MultiQueuesEnabled string `json:"multi_queues_enabled"`
- PlacementPolicy struct {
- Affinity string `json:"affinity"`
- } `json:"placement_policy"`
- SmallIcon struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"small_icon"`
- StartPaused string `json:"start_paused"`
- StorageErrorResumeBehaviour string `json:"storage_error_resume_behaviour"`
- Cluster struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"cluster,omitempty"`
- TimeZone struct {
- Name string `json:"name"`
- } `json:"time_zone,omitempty"`
- CPUProfile struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"cpu_profile,omitempty"`
- Initialization struct {
- AuthorizedSSHKeys string `json:"authorized_ssh_keys"`
- CloudInitNetworkProtocol string `json:"cloud_init_network_protocol"`
- CustomScript string `json:"custom_script"`
- HostName string `json:"host_name"`
- NicConfigurations struct {
- } `json:"nic_configurations"`
- RegenerateSSHKeys string `json:"regenerate_ssh_keys"`
- UserName string `json:"user_name"`
- } `json:"initialization,omitempty"`
- } `json:"template"`
- }
- type templateListResponse struct {
- Data []struct {
- Name string `json:"name"`
- } `json:"Data"`
- Message string `json:"message"`
- Origin string `json:"origin"`
- Code int `json:"code"`
- }
- user := c.Get("user").(*jwt.Token)
- claims := user.Claims.(jwt.MapClaims)
- _sha256 := sha256.Sum256([]byte(string(claims["name"].(string))))
- var hashChannel_ = make(chan []byte, 1)
- hashChannel_ <- _sha256[:]
- token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
- _BA := strings.Split(token, ";")
- BA := _BA[len(_BA)-2]
- url := OvirtURL + "/ovirt-engine/api/templates?filter=true&search=Cloud"
- client := &http.Client{}
- req, err := http.NewRequest("GET", url, nil)
- if err != nil {
- fmt.Println(err)
- }
- req.Header.Add("Version", "4")
- req.Header.Add("Accept", "application/json")
- req.Header.Add("Authorization", BA)
- res, err := client.Do(req)
- body, err := ioutil.ReadAll(res.Body)
- defer res.Body.Close()
- _templateList := templateList{}
- err = json.Unmarshal(body, &_templateList)
- //fmt.Println("resp:",string(body))
- _templateListResponse := templateListResponse{
- Data: nil,
- Message: "Done",
- Origin: "ListTemplate",
- Code: 1000,
- }
- _Data := _templateListResponse.Data
- y := struct {
- Name string `json:"name"`
- }{}
- for _, v := range _templateList.Template {
- y.Name = v.Name
- _Data = append(_Data, y)
- }
- _templateListResponse.Data = _Data
- return c.JSON(http.StatusOK, _templateListResponse)
- //return c.String(http.StatusOK, string(b))
- }
- func (o ovirt) vmHistory(c echo.Context) error {
- type VMStatistics struct {
- Statistic []struct {
- Kind string `json:"kind"`
- Type string `json:"type"`
- Unit string `json:"unit"`
- Values struct {
- Value []struct {
- Datum int64 `json:"datum"`
- } `json:"value"`
- } `json:"values"`
- VM struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"vm,omitempty"`
- Name string `json:"name"`
- Description string `json:"description"`
- Href string `json:"href,omitempty"`
- ID string `json:"id"`
- } `json:"statistic"`
- }
- type VMStatisticsResponse struct {
- Data []struct {
- Kind string `json:"kind"`
- Type string `json:"type"`
- Unit string `json:"unit"`
- Values struct {
- Value []struct {
- Datum int64 `json:"datum"`
- } `json:"value"`
- } `json:"values"`
- Name string `json:"name"`
- Description string `json:"description"`
- //Href string `json:"href,omitempty"`
- //ID string `json:"id"`
- } `json:"statistic"`
- Message string `json:"message"`
- Origin string `json:"origin"`
- Code int `json:"code"`
- }
- user := c.Get("user").(*jwt.Token)
- claims := user.Claims.(jwt.MapClaims)
- _sha256 := sha256.Sum256([]byte(string(claims["name"].(string))))
- var hashChannel_ = make(chan []byte, 1)
- hashChannel_ <- _sha256[:]
- token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
- _BA := strings.Split(token, ";")
- BA := _BA[len(_BA)-2]
- vmuuid := c.FormValue("VmUUID")
- url := OvirtURL + "/ovirt-engine/api/vms/" + vmuuid + "/statistics"
- client := &http.Client{}
- req, err := http.NewRequest("GET", url, nil)
- if err != nil {
- fmt.Println(err)
- }
- req.Header.Add("Version", "4")
- req.Header.Add("Accept", "application/json")
- req.Header.Add("Authorization", BA)
- res, err := client.Do(req)
- defer res.Body.Close()
- body, err := ioutil.ReadAll(res.Body)
- _VMStatistics := VMStatistics{}
- err = json.Unmarshal(body, &_VMStatistics)
- _VMStatisticsResponse := VMStatisticsResponse{
- Data: nil,
- Message: "Done",
- Origin: "vmHistory",
- Code: 1000,
- }
- _Data := _VMStatisticsResponse.Data
- y := struct {
- Kind string `json:"kind"`
- Type string `json:"type"`
- Unit string `json:"unit"`
- Values struct {
- Value []struct {
- Datum int64 `json:"datum"`
- } `json:"value"`
- } `json:"values"`
- Name string `json:"name"`
- Description string `json:"description"`
- //Href string `json:"href,omitempty"`
- //ID string `json:"id"`
- }{}
- for _, v := range _VMStatistics.Statistic {
- y.Kind = v.Kind
- y.Unit = v.Unit
- y.Type = v.Type
- y.Values = v.Values
- y.Name = v.Name
- y.Description = v.Description
- _Data = append(_Data, y)
- }
- _VMStatisticsResponse.Data = _Data
- return c.JSON(http.StatusOK, _VMStatisticsResponse)
- }
- func (o ovirt) SSHKeyGen(c echo.Context) error {
- type SSHKeyGenResponse struct {
- Message string `json:"message"`
- Origin string `json:"origin"`
- Code int `json:"code"`
- }
- user := c.Get("user").(*jwt.Token)
- claims := user.Claims.(jwt.MapClaims)
- email := fmt.Sprintf("%s", claims["mail"])
- fmt.Println(email)
- mrand.Seed(time.Now().Unix())
- var output strings.Builder
- //Only lowercase
- charSet := "abcdedfghijklmnopqrstABCDEFGHIJKLMNOP0123456789"
- length := 20
- for i := 0; i < length; i++ {
- random := mrand.Intn(len(charSet))
- randomChar := charSet[random]
- output.WriteString(string(randomChar))
- }
- publicKeyBlock := &pem.Block{}
- {
- // generate key
- privatekey, err := rsa.GenerateKey(rand.Reader, 1024)
- if err != nil {
- fmt.Printf("Cannot generate RSA key\n")
- //os.Exit(1)
- }
- publickey := &privatekey.PublicKey
- // dump private key to file
- var privateKeyBytes []byte = x509.MarshalPKCS1PrivateKey(privatekey)
- privateKeyBlock := &pem.Block{
- Type: "RSA PRIVATE KEY",
- Bytes: privateKeyBytes,
- }
- privatePem, err := os.Create("/tmp/" + output.String() + "-private.pem")
- if err != nil {
- fmt.Printf("error when create private.pem: %s \n", err)
- //os.Exit(1)
- }
- err = pem.Encode(privatePem, privateKeyBlock)
- if err != nil {
- fmt.Printf("error when encode private pem: %s \n", err)
- //os.Exit(1)
- }
- // dump public key to file
- publicKeyBytes, err := x509.MarshalPKIXPublicKey(publickey)
- if err != nil {
- fmt.Printf("error when dumping publickey: %s \n", err)
- //os.Exit(1)
- }
- publicKeyBlock = &pem.Block{
- Type: "PUBLIC KEY",
- Bytes: publicKeyBytes,
- }
- publicPem, err := os.Create("/tmp/" + output.String() + "-public.pem")
- if err != nil {
- fmt.Printf("error when create public.pem: %s \n", err)
- //os.Exit(1)
- }
- err = pem.Encode(publicPem, publicKeyBlock)
- if err != nil {
- fmt.Printf("error when encode public pem: %s \n", err)
- //os.Exit(1)
- }
- 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"})
- }
- _SSHKeyGenResponse := SSHKeyGenResponse{
- Message: string(pem.EncodeToMemory(publicKeyBlock)),
- Origin: "SSHKeyGen",
- Code: 1000,
- }
- return c.JSON(http.StatusOK, _SSHKeyGenResponse)
- }
- func (o ovirt) ovirtSuspend(c echo.Context) error {
- type VMSuspend struct {
- Async string `json:"async"`
- Job struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"job"`
- Status string `json:"status"`
- Href string `json:"href"`
- ID string `json:"id"`
- Link []struct {
- Href string `json:"href"`
- Rel string `json:"rel"`
- } `json:"link"`
- }
- vmuuid := c.FormValue("VmUUID")
- user := c.Get("user").(*jwt.Token)
- claims := user.Claims.(jwt.MapClaims)
- _sha256 := sha256.Sum256([]byte(string(claims["name"].(string))))
- var hashChannel_ = make(chan []byte, 1)
- hashChannel_ <- _sha256[:]
- token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
- _BA := strings.Split(token, ";")
- BA := _BA[len(_BA)-2]
- url := OvirtURL + "/ovirt-engine/api/vms/" + vmuuid + "/suspend"
- method := "POST"
- payload := strings.NewReader(`{
- "async":"true"
- }`)
- client := &http.Client{}
- req, err := http.NewRequest(method, url, payload)
- if err != nil {
- fmt.Println(err)
- }
- req.Header.Add("Version", "4")
- req.Header.Add("Accept", "application/json")
- ///TODO: BA
- req.Header.Add("Authorization", BA)
- req.Header.Add("Content-Type", "application/json")
- res, err := client.Do(req)
- if err != nil {
- fmt.Println("Error 1", err)
- }
- defer res.Body.Close()
- body, err := ioutil.ReadAll(res.Body)
- //fmt.Println(res.Status)
- //fmt.Println(res.Body)
- if err != nil {
- //fmt.Println("Error 3", err)
- fmt.Println(err)
- }
- _VMSuspend := VMSuspend{}
- err = json.Unmarshal(body, &_VMSuspend)
- if err != nil {
- //fmt.Println("Error 4", err)
- fmt.Println(err)
- }
- //fmt.Println(_VMSuspend)
- db, err := sql.Open("mysql", MySQLUSER+":"+MySQLPASS+"@tcp(127.0.0.1:3306)/zicloud")
- if err != nil {
- }
- update, err := db.Query("update service_profile set active='-2' where uuid='" + vmuuid + "'")
- defer db.Close()
- if err != nil {
- }
- defer update.Close()
- type VMSuspendResponse struct {
- Message string `json:"message"`
- Origin string `json:"origin"`
- Code int `json:"code"`
- }
- resp := VMSuspendResponse{
- Message: "Done",
- Origin: "ovirtSuspend",
- Code: 1000,
- }
- return c.JSON(http.StatusOK, resp)
- }
- func (o ovirt) BillingSuspend(c echo.Context) error {
- type VMSuspend struct {
- Async string `json:"async"`
- Job struct {
- Href string `json:"href"`
- ID string `json:"id"`
- } `json:"job"`
- Status string `json:"status"`
- Href string `json:"href"`
- ID string `json:"id"`
- Link []struct {
- Href string `json:"href"`
- Rel string `json:"rel"`
- } `json:"link"`
- }
- vmuuid := c.FormValue("VmUUID")
- //user := c.Get("user").(*jwt.Token)
- //claims := user.Claims.(jwt.MapClaims)
- //_sha256 := sha256.Sum256([]byte(string(claims["name"].(string))))
- //var hashChannel_ = make(chan []byte, 1)
- //hashChannel_ <- _sha256[:]
- //token := decrypt(<-hashChannel_, claims["IPAToken"].(string))
- //_BA := strings.Split(token, ";")
- //BA := _BA[len(_BA)-2]
- url := OvirtURL + "/ovirt-engine/api/vms/" + vmuuid + "/suspend"
- method := "POST"
- payload := strings.NewReader(`{
- "async":"true"
- }`)
- client := &http.Client{}
- req, err := http.NewRequest(method, url, payload)
- if err != nil {
- fmt.Println(err)
- }
- req.Header.Add("Version", "4")
- req.Header.Add("Accept", "application/json")
- ///TODO: BA
- req.Header.Add("Authorization", "Basic YWRtaW5AaW50ZXJuYWw6a2VsYW5zaCBqMw==")
- req.Header.Add("Content-Type", "application/json")
- res, err := client.Do(req)
- if err != nil {
- fmt.Println("Error 1", err)
- }
- defer res.Body.Close()
- body, err := ioutil.ReadAll(res.Body)
- //fmt.Println(res.Status)
- //fmt.Println(res.Body)
- if err != nil {
- //fmt.Println("Error 3", err)
- fmt.Println(err)
- }
- _VMSuspend := VMSuspend{}
- err = json.Unmarshal(body, &_VMSuspend)
- if err != nil {
- //fmt.Println("Error 4", err)
- fmt.Println(err)
- }
- //fmt.Println(_VMSuspend)
- db, err := sql.Open("mysql", MySQLUSER+":"+MySQLPASS+"@tcp(127.0.0.1:3306)/zicloud")
- if err != nil {
- }
- ///TODO: Sanitize Input variables
- update, err := db.Query("update service_profile set active='-3' where uuid='" + vmuuid + "'")
- defer db.Close()
- if err != nil {
- }
- defer update.Close()
- type VMSuspendResponse struct {
- Message string `json:"message"`
- Origin string `json:"origin"`
- Code int `json:"code"`
- }
- resp := VMSuspendResponse{
- Message: "Done",
- Origin: "ovirtSuspend",
- Code: 1000,
- }
- return c.JSON(http.StatusOK, resp)
- }
|