github.com/cloud-foundations/dominator@v0.0.0-20221004181915-6e4fee580046/hypervisor/httpd/listVMs.go (about) 1 package httpd 2 3 import ( 4 "bufio" 5 "fmt" 6 "net" 7 "net/http" 8 9 "github.com/Cloud-Foundations/Dominator/lib/format" 10 "github.com/Cloud-Foundations/Dominator/lib/html" 11 "github.com/Cloud-Foundations/Dominator/lib/url" 12 proto "github.com/Cloud-Foundations/Dominator/proto/hypervisor" 13 ) 14 15 func (s state) listVMsHandler(w http.ResponseWriter, req *http.Request) { 16 parsedQuery := url.ParseQuery(req.URL) 17 writer := bufio.NewWriter(w) 18 defer writer.Flush() 19 ipAddrs := s.manager.ListVMs(proto.ListVMsRequest{Sort: true}) 20 matchState := parsedQuery.Table["state"] 21 if parsedQuery.OutputType() == url.OutputTypeText && matchState == "" { 22 for _, ipAddr := range ipAddrs { 23 fmt.Fprintln(writer, ipAddr) 24 } 25 return 26 } 27 var tw *html.TableWriter 28 if parsedQuery.OutputType() == url.OutputTypeHtml { 29 fmt.Fprintf(writer, "<title>List of VMs</title>\n") 30 fmt.Fprintln(writer, `<style> 31 table, th, td { 32 border-collapse: collapse; 33 } 34 </style>`) 35 fmt.Fprintln(writer, "<body>") 36 fmt.Fprintln(writer, `<table border="1" style="width:100%">`) 37 tw, _ = html.NewTableWriter(writer, true, "IP Addr", "MAC Addr", 38 "Name(tag)", "State", "RAM", "CPU", "Num Volumes", "Storage", 39 "Primary Owner") 40 } 41 for _, ipAddr := range ipAddrs { 42 vm, err := s.manager.GetVmInfo(net.ParseIP(ipAddr)) 43 if err != nil { 44 continue 45 } 46 if matchState != "" && matchState != vm.State.String() { 47 continue 48 } 49 switch parsedQuery.OutputType() { 50 case url.OutputTypeText: 51 fmt.Fprintln(writer, ipAddr) 52 case url.OutputTypeHtml: 53 var background string 54 if vm.Uncommitted { 55 background = "yellow" 56 } 57 tw.WriteRow("", background, 58 fmt.Sprintf("<a href=\"showVM?%s\">%s</a>", ipAddr, ipAddr), 59 vm.Address.MacAddress, 60 vm.Tags["Name"], 61 vm.State.String(), 62 format.FormatBytes(vm.MemoryInMiB<<20), 63 fmt.Sprintf("%g", float64(vm.MilliCPUs)*1e-3), 64 numVolumesTableEntry(vm), 65 storageTotalTableEntry(vm), 66 vm.OwnerUsers[0], 67 ) 68 } 69 } 70 switch parsedQuery.OutputType() { 71 case url.OutputTypeHtml: 72 fmt.Fprintln(writer, "</table>") 73 fmt.Fprintln(writer, "</body>") 74 } 75 } 76 77 func numVolumesTableEntry(vm proto.VmInfo) string { 78 var comment string 79 for _, volume := range vm.Volumes { 80 if comment == "" && volume.Format != proto.VolumeFormatRaw { 81 comment = `<font style="color:grey;font-size:12px"> (!RAW)</font>` 82 } 83 } 84 return fmt.Sprintf("%d%s", len(vm.Volumes), comment) 85 } 86 87 func storageTotalTableEntry(vm proto.VmInfo) string { 88 var storage uint64 89 for _, volume := range vm.Volumes { 90 storage += volume.Size 91 } 92 return format.FormatBytes(storage) 93 }