github.com/Cloud-Foundations/Dominator@v0.3.4/fleetmanager/hypervisors/showVM.go (about)

     1  package hypervisors
     2  
     3  import (
     4  	"bufio"
     5  	"fmt"
     6  	"net/http"
     7  
     8  	"github.com/Cloud-Foundations/Dominator/lib/constants"
     9  	"github.com/Cloud-Foundations/Dominator/lib/json"
    10  	"github.com/Cloud-Foundations/Dominator/lib/url"
    11  	hyper_proto "github.com/Cloud-Foundations/Dominator/proto/hypervisor"
    12  )
    13  
    14  // getVmInfoAndHypervisor returns VM info if it exists (else nil) and the
    15  // hostname of its Hypervisor if the Hypervisor is OK (else it returns an empty
    16  // string).
    17  func (m *Manager) getVmInfoAndHypervisor(vmIpAddr string) (
    18  	*hyper_proto.VmInfo, string) {
    19  	m.mutex.RLock()
    20  	defer m.mutex.RUnlock()
    21  	vm := m.vms[vmIpAddr]
    22  	if vm == nil {
    23  		return nil, ""
    24  	}
    25  	if vm.hypervisor.probeStatus == probeStatusConnected {
    26  		return &vm.VmInfo, vm.hypervisor.machine.Hostname
    27  	}
    28  	return &vm.VmInfo, ""
    29  }
    30  
    31  func (m *Manager) showVmHandler(w http.ResponseWriter,
    32  	req *http.Request) {
    33  	parsedQuery := url.ParseQuery(req.URL)
    34  	if len(parsedQuery.Flags) != 1 {
    35  		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
    36  		w.WriteHeader(http.StatusBadRequest)
    37  		return
    38  	}
    39  	var ipAddr string
    40  	for name := range parsedQuery.Flags {
    41  		ipAddr = name
    42  	}
    43  	vmInfo, hypervisorHostname := m.getVmInfoAndHypervisor(ipAddr)
    44  	if vmInfo == nil {
    45  		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
    46  		w.WriteHeader(http.StatusNotFound)
    47  		return
    48  	}
    49  	if hypervisorHostname != "" {
    50  		http.Redirect(w, req,
    51  			fmt.Sprintf("http://%s:%d/showVM?%s",
    52  				hypervisorHostname, constants.HypervisorPortNumber, ipAddr),
    53  			http.StatusFound)
    54  	}
    55  	writer := bufio.NewWriter(w)
    56  	defer writer.Flush()
    57  	json.WriteWithIndent(writer, "    ", vmInfo)
    58  }