change logging to file
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
2023-05-23 16:58:37 +10:00
parent 55f6889640
commit 06c7b0cc14

67
main.go
View File

@@ -5,6 +5,7 @@ import (
"encoding/json"
"flag"
"fmt"
"log"
"net/url"
"os"
"sort"
@@ -57,7 +58,7 @@ func getEvents(eventTypes []string, entities []types.ManagedObjectReference, beg
fmt.Fprintf(os.Stderr, "Error getting vCenter time: %s\n", err)
os.Exit(1)
} else {
fmt.Fprintf(os.Stderr, "vCenter time is '%v'\n", now)
log.Printf("vCenter time is '%v'\n", now)
}
m := event.NewManager(c.Client)
@@ -75,7 +76,7 @@ func getEvents(eventTypes []string, entities []types.ManagedObjectReference, beg
},
}
if len(entities) > 0 {
fmt.Fprintf(os.Stderr, "getEvents setting entity '%v' to filter\n", entities[0])
log.Printf("getEvents setting entity '%v' to filter\n", entities[0])
filter.Entity = &types.EventFilterSpecByEntity{
Entity: entities[0],
Recursion: types.EventFilterSpecRecursionOptionAll,
@@ -107,8 +108,8 @@ func getEvents(eventTypes []string, entities []types.ManagedObjectReference, beg
event := events[i].GetEvent()
returnEvents = append(returnEvents, *event)
//kind := reflect.TypeOf(events[i]).Elem().Name()
//fmt.Fprintf(os.Stderr, "%d [%s] [%s] %s\n", event.Key, event.CreatedTime.In(location).Format(time.ANSIC), kind, event.FullFormattedMessage)
fmt.Fprintf(os.Stderr, "%d [%s] %s\n", event.Key, event.CreatedTime.In(location).Format(time.ANSIC), event.FullFormattedMessage)
//log.Printf("%d [%s] [%s] %s\n", event.Key, event.CreatedTime.In(location).Format(time.ANSIC), kind, event.FullFormattedMessage)
log.Printf("%d [%s] %s\n", event.Key, event.CreatedTime.In(location).Format(time.ANSIC), event.FullFormattedMessage)
}
}
@@ -121,15 +122,15 @@ func getCluster(name string) mo.ClusterComputeResource {
cv, _ := m.CreateContainerView(ctx, c.ServiceContent.RootFolder, []string{"ClusterComputeResource"}, true)
var clusters []mo.ClusterComputeResource
fmt.Fprintf(os.Stderr, "Searching for Cluster '%s'\n", name)
log.Printf("Searching for Cluster '%s'\n", name)
err := cv.Retrieve(ctx, []string{"ClusterComputeResource"}, []string{"summary", "name"}, &clusters)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed searching for Cluster %s : %s\n", name, err)
log.Printf("Failed searching for Cluster %s : %s\n", name, err)
return mo.ClusterComputeResource{}
} else {
for _, cluster := range clusters {
if cluster.Name == name {
fmt.Fprintf(os.Stderr, "Found corresponding Cluster with MoRef '%s'\n", cluster.Reference())
log.Printf("Found corresponding Cluster with MoRef '%s'\n", cluster.Reference())
return cluster
}
}
@@ -145,15 +146,15 @@ func getVM(name string) mo.VirtualMachine {
cv, _ := m.CreateContainerView(ctx, c.ServiceContent.RootFolder, []string{"VirtualMachine"}, true)
var vms []mo.VirtualMachine
fmt.Fprintf(os.Stderr, "Searching for VM '%s'\n", name)
log.Printf("Searching for VM '%s'\n", name)
err := cv.Retrieve(ctx, []string{"VirtualMachine"}, []string{"summary", "name"}, &vms)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed searching for VM %s : %s\n", name, err)
log.Printf("Failed searching for VM %s : %s\n", name, err)
return mo.VirtualMachine{}
} else {
for _, vm := range vms {
if vm.Name == name {
fmt.Fprintf(os.Stderr, "Found corresponding VM with MoRef '%s'\n", vm.Reference())
log.Printf("Found corresponding VM with MoRef '%s'\n", vm.Reference())
return vm
}
}
@@ -169,15 +170,15 @@ func getVmInCluster(name string, cluster types.ManagedObjectReference) mo.Virtua
cv, _ := m.CreateContainerView(ctx, cluster, []string{"VirtualMachine"}, true)
var vms []mo.VirtualMachine
fmt.Fprintf(os.Stderr, "Searching for VM '%s'\n", name)
log.Printf("Searching for VM '%s'\n", name)
err := cv.Retrieve(ctx, []string{"VirtualMachine"}, []string{"summary", "name"}, &vms)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed searching for VM %s : %s\n", name, err)
log.Printf("Failed searching for VM %s : %s\n", name, err)
return mo.VirtualMachine{}
} else {
for _, vm := range vms {
if vm.Name == name {
fmt.Fprintf(os.Stderr, "Found corresponding VM with MoRef '%s'\n", vm.Reference())
log.Printf("Found corresponding VM with MoRef '%s'\n", vm.Reference())
return vm
}
}
@@ -201,7 +202,15 @@ func main() {
// So we can convert vCenter UTC to our local timezone
location, _ = time.LoadLocation(*vTZ)
fmt.Fprintf(os.Stderr, "Starting execution. Built on %s from sha1 %s\n", buildTime, sha1ver)
// Print logs to file
f, err := os.OpenFile("log.txt", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Fatalf("error opening file: %v", err)
}
defer f.Close()
log.SetOutput(f)
log.Printf("Starting execution. Built on %s from sha1 %s\n", buildTime, sha1ver)
u, err := url.Parse(*vURL)
if err != nil {
@@ -210,11 +219,11 @@ func main() {
} else {
if !strings.HasSuffix(u.Path, "/sdk") {
u.Path, _ = url.JoinPath(u.Path, "/sdk")
fmt.Fprintf(os.Stderr, "Updated vCenter URL to '%v'\n", u)
log.Printf("Updated vCenter URL to '%v'\n", u)
}
}
fmt.Fprintf(os.Stderr, "Connecting to vCenter %s\n", u)
log.Printf("Connecting to vCenter %s\n", u)
u.User = url.UserPassword(*vUser, *vPass)
ctx, cancel = context.WithCancel(context.Background())
@@ -230,11 +239,11 @@ func main() {
//finder := find.NewFinder(c.Client)
fmt.Fprintf(os.Stderr, "Searching for hostfailure events\n")
log.Printf("Searching for hostfailure events\n")
hostFailures := getEvents([]string{"com.vmware.vc.HA.DasHostFailedEvent"}, []types.ManagedObjectReference{}, *begin, *end)
if len(hostFailures) > 0 {
fmt.Fprintf(os.Stderr, "Found at least one host failure, proceeding with VM restart search\n")
log.Printf("Found at least one host failure, proceeding with VM restart search\n")
vmFailures := getEvents([]string{"com.vmware.vc.ha.VmRestartedByHAEvent"}, []types.ManagedObjectReference{}, *begin, *end)
// Sort the host failure events by time
@@ -248,7 +257,7 @@ func main() {
var possibleHosts []types.Event
event := vmFailures[i]
vmRestartTime := event.CreatedTime.In(location)
fmt.Fprintf(os.Stderr, "Failure event for VM '%s' restarted in cluster '%s'\n", event.Vm.Name, event.ComputeResource.Name)
log.Printf("Failure event for VM '%s' restarted in cluster '%s'\n", event.Vm.Name, event.ComputeResource.Name)
// Get a reference to the cluster mentioned
cluster := getCluster((event.ComputeResource.Name))
@@ -257,7 +266,7 @@ func main() {
// Use VmDisconnectedEvent to see which host this VM was on
disconnectedEvents := getEvents([]string{"VmDisconnectedEvent"}, []types.ManagedObjectReference{vm.Reference()}, *begin, *end)
fmt.Fprintf(os.Stderr, "Retrieved '%d' corresponding events.\n", len(disconnectedEvents))
log.Printf("Retrieved '%d' corresponding events.\n", len(disconnectedEvents))
// Determine which host the VM was previoulsy running on
if len(disconnectedEvents) > 0 {
@@ -267,7 +276,7 @@ func main() {
})
disconnectedHost := disconnectedEvents[0]
fmt.Fprintf(os.Stderr, "VM was running on host '%s' previously\n", disconnectedHost.Host.Name)
log.Printf("VM was running on host '%s' previously\n", disconnectedHost.Host.Name)
// Capture all the failure events for this host
for _, hostEvent := range hostFailures {
@@ -276,7 +285,7 @@ func main() {
}
}
} else {
fmt.Fprintf(os.Stderr, "could not determine previous host for this VM. Filtering all host failures for events prior to VM restart time '%s'\n", vmRestartTime)
log.Printf("could not determine previous host for this VM. Filtering all host failures for events prior to VM restart time '%s'\n", vmRestartTime)
// Search for host failures
for _, hostEvent := range hostFailures {
@@ -285,32 +294,32 @@ func main() {
}
}
fmt.Fprintf(os.Stderr, "Based on event times there were %d possible hosts this VM was running on\n", len(possibleHosts))
log.Printf("Based on event times there were %d possible hosts this VM was running on\n", len(possibleHosts))
if len(possibleHosts) == 0 {
fmt.Fprintf(os.Stderr, "No ESXi outage events happened before VM %s restart event at %s, skipping this event.\n", event.Vm.Name, vmRestartTime)
log.Printf("No ESXi outage events happened before VM %s restart event at %s, skipping this event.\n", event.Vm.Name, vmRestartTime)
continue
}
}
if len(possibleHosts) == 1 {
fmt.Fprintf(os.Stderr, "Found a single host failure event relating to VM %s\n", event.Vm.Name)
fmt.Fprintf(os.Stderr, "Failed host was '%s', using outage start time of '%s'\n", possibleHosts[0].Host.Name, possibleHosts[0].CreatedTime.In(location))
log.Printf("Found a single host failure event relating to VM %s\n", event.Vm.Name)
log.Printf("Failed host was '%s', using outage start time of '%s'\n", possibleHosts[0].Host.Name, possibleHosts[0].CreatedTime.In(location))
failedHost = possibleHosts[0].Host.Name
outageStart = possibleHosts[0].CreatedTime.In(location)
restartTime = vmRestartTime
} else if len(possibleHosts) > 1 {
fmt.Fprintf(os.Stderr, "Found multiple host failure events relating to VM %s\n", event.Vm.Name)
log.Printf("Found multiple host failure events relating to VM %s\n", event.Vm.Name)
// possible hosts is sorted by time, so use the last value if there are multiple
lastIndex := len(possibleHosts) - 1
fmt.Fprintf(os.Stderr, "Failed host was '%s', using outage start time of '%s'\n", possibleHosts[lastIndex].Host.Name, possibleHosts[lastIndex].CreatedTime.In(location))
log.Printf("Failed host was '%s', using outage start time of '%s'\n", possibleHosts[lastIndex].Host.Name, possibleHosts[lastIndex].CreatedTime.In(location))
failedHost = possibleHosts[lastIndex].Host.Name
outageStart = possibleHosts[lastIndex].CreatedTime.In(location)
restartTime = vmRestartTime
} else {
fmt.Fprintf(os.Stderr, "Didn't get anything useful!\n")
log.Printf("Didn't get anything useful!\n")
}
/*