本文整理汇总了Golang中github.com/evergreen-ci/evergreen/model/host.ById函数的典型用法代码示例。如果您正苦于以下问题:Golang ById函数的具体用法?Golang ById怎么用?Golang ById使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ById函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: hostPage
func (uis *UIServer) hostPage(w http.ResponseWriter, r *http.Request) {
projCtx := MustHaveProjectContext(r)
vars := mux.Vars(r)
id := vars["host_id"]
h, err := host.FindOne(host.ById(id))
if err != nil {
uis.LoggedError(w, r, http.StatusInternalServerError, err)
return
}
if h == nil {
http.Error(w, "Host not found", http.StatusNotFound)
return
}
events, err := event.Find(event.MostRecentHostEvents(id, 50))
if err != nil {
uis.LoggedError(w, r, http.StatusInternalServerError, err)
return
}
flashes := PopFlashes(uis.CookieStore, r, w)
uis.WriteHTML(w, http.StatusOK, struct {
Flashes []interface{}
Events []event.Event
Host *host.Host
User *user.DBUser
ProjectData projectContext
}{flashes, events, h, GetUser(r), projCtx},
"base", "host.html", "base_angular.html", "menu.html")
}
示例2: GetDistro
// GetDistro loads the task's distro and sends it to the requester.
func (as *APIServer) GetDistro(w http.ResponseWriter, r *http.Request) {
task := MustHaveTask(r)
// Get the distro for this task
h, err := host.FindOne(host.ByRunningTaskId(task.Id))
if err != nil {
as.LoggedError(w, r, http.StatusInternalServerError, err)
return
}
// Fall back to checking host field on task doc
if h == nil && len(task.HostId) > 0 {
h, err = host.FindOne(host.ById(task.HostId))
if err != nil {
as.LoggedError(w, r, http.StatusInternalServerError, err)
return
}
h.SetRunningTask(task.Id, h.AgentRevision, h.TaskDispatchTime)
}
if h == nil {
message := fmt.Errorf("No host found running task %v", task.Id)
as.LoggedError(w, r, http.StatusInternalServerError, message)
return
}
// agent can't properly unmarshal provider settings map
h.Distro.ProviderSettings = nil
as.WriteJSON(w, http.StatusOK, h.Distro)
}
示例3: StartTask
func (as *APIServer) StartTask(w http.ResponseWriter, r *http.Request) {
task := MustHaveTask(r)
if !getGlobalLock(r.RemoteAddr, task.Id) {
as.LoggedError(w, r, http.StatusInternalServerError, ErrLockTimeout)
return
}
defer releaseGlobalLock(r.RemoteAddr, task.Id)
evergreen.Logger.Logf(slogger.INFO, "Marking task started: %v", task.Id)
taskStartInfo := &apimodels.TaskStartRequest{}
if err := util.ReadJSONInto(r.Body, taskStartInfo); err != nil {
http.Error(w, fmt.Sprintf("Error reading task start request for %v: %v", task.Id, err), http.StatusBadRequest)
return
}
if err := task.MarkStart(); err != nil {
message := fmt.Errorf("Error marking task '%v' started: %v", task.Id, err)
as.LoggedError(w, r, http.StatusInternalServerError, message)
return
}
h, err := host.FindOne(host.ByRunningTaskId(task.Id))
if err != nil {
message := fmt.Errorf("Error finding host running task %v: %v", task.Id, err)
as.LoggedError(w, r, http.StatusInternalServerError, message)
return
}
// Fall back to checking host field on task doc
if h == nil && len(task.HostId) > 0 {
evergreen.Logger.Logf(slogger.DEBUG, "Falling back to host field of task: %v", task.Id)
h, err = host.FindOne(host.ById(task.HostId))
if err != nil {
as.LoggedError(w, r, http.StatusInternalServerError, err)
return
}
h.SetRunningTask(task.Id, h.AgentRevision, h.TaskDispatchTime)
}
if h == nil {
message := fmt.Errorf("No host found running task %v", task.Id)
as.LoggedError(w, r, http.StatusInternalServerError, message)
return
}
if err := h.SetTaskPid(taskStartInfo.Pid); err != nil {
message := fmt.Errorf("Error calling set pid on task %v : %v", task.Id, err)
as.LoggedError(w, r, http.StatusInternalServerError, message)
return
}
as.WriteJSON(w, http.StatusOK, fmt.Sprintf("Task %v started on host %v", task.Id, h.Id))
}
示例4: getHostData
func getHostData(hostId string) (*uiHost, error) {
hostAsUI := &uiHost{}
dbHost, err := host.FindOne(host.ById(hostId))
if err != nil {
return nil, err
}
if dbHost == nil {
return nil, fmt.Errorf("Could not find host")
}
hostAsUI.Host = *dbHost
return hostAsUI, nil
}
示例5: getHostFromRequest
// Get the host with the id specified in the request
func getHostFromRequest(r *http.Request) (*host.Host, error) {
// get id and secret from the request.
vars := mux.Vars(r)
tag := vars["tag"]
if len(tag) == 0 {
return nil, fmt.Errorf("no host tag supplied")
}
// find the host
host, err := host.FindOne(host.ById(tag))
if host == nil {
return nil, fmt.Errorf("no host with tag: %v", tag)
}
if err != nil {
return nil, err
}
return host, nil
}
示例6: hostInfo
// returns info on the host specified
func (as *APIServer) hostInfo(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
instanceId := vars["instance_id"]
host, err := host.FindOne(host.ById(instanceId))
if err != nil {
as.LoggedError(w, r, http.StatusInternalServerError, err)
return
}
if host == nil {
http.Error(w, "not found", http.StatusNotFound)
return
}
as.WriteJSON(w, http.StatusOK, spawnResponse{HostInfo: *host})
}
示例7: modifyHost
func (as *APIServer) modifyHost(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
instanceId := vars["instance_id"]
hostAction := r.FormValue("action")
host, err := host.FindOne(host.ById(instanceId))
if err != nil {
as.LoggedError(w, r, http.StatusInternalServerError, err)
return
}
if host == nil {
http.Error(w, "not found", http.StatusNotFound)
return
}
user := GetUser(r)
if user == nil || user.Id != host.StartedBy {
message := fmt.Sprintf("Only %v is authorized to terminate this host", host.StartedBy)
http.Error(w, message, http.StatusUnauthorized)
return
}
switch hostAction {
case "terminate":
if host.Status == evergreen.HostTerminated {
message := fmt.Sprintf("Host %v is already terminated", host.Id)
http.Error(w, message, http.StatusBadRequest)
return
}
cloudHost, err := providers.GetCloudHost(host, &as.Settings)
if err != nil {
as.LoggedError(w, r, http.StatusInternalServerError, err)
return
}
if err = cloudHost.TerminateInstance(); err != nil {
as.LoggedError(w, r, http.StatusInternalServerError, fmt.Errorf("Failed to terminate spawn host: %v", err))
return
}
as.WriteJSON(w, http.StatusOK, spawnResponse{HostInfo: *host})
default:
http.Error(w, fmt.Sprintf("Unrecognized action %v", hostAction), http.StatusBadRequest)
}
}
示例8: modifyHost
func (uis *UIServer) modifyHost(w http.ResponseWriter, r *http.Request) {
_ = MustHaveUser(r)
vars := mux.Vars(r)
id := vars["host_id"]
host, err := host.FindOne(host.ById(id))
if err != nil {
uis.LoggedError(w, r, http.StatusInternalServerError, err)
return
}
if host == nil {
http.Error(w, "Host not found", http.StatusNotFound)
return
}
opts := &uiParams{}
err = util.ReadJSONInto(r.Body, opts)
if err != nil {
uis.LoggedError(w, r, http.StatusBadRequest, err)
return
}
// determine what action needs to be taken
switch opts.Action {
case "updateStatus":
currentStatus := host.Status
newStatus := opts.Status
if !util.SliceContains(validUpdateToStatuses, newStatus) {
http.Error(w, fmt.Sprintf("'%v' is not a valid status", newStatus), http.StatusBadRequest)
return
}
err := host.SetStatus(newStatus)
if err != nil {
uis.LoggedError(w, r, http.StatusInternalServerError, fmt.Errorf("Error updating host: %v", err))
return
}
msg := NewSuccessFlash(fmt.Sprintf("Host status successfully updated from '%v' to '%v'", currentStatus, host.Status))
PushFlash(uis.CookieStore, r, w, msg)
uis.WriteJSON(w, http.StatusOK, "Successfully updated host status")
default:
uis.WriteJSON(w, http.StatusBadRequest, fmt.Sprintf("Unrecognized action: %v", opts.Action))
}
}
示例9: cleanUpTask
// function to clean up a single task
func cleanUpTask(wrapper doomedTaskWrapper, projects map[string]model.Project) error {
// find the appropriate project for the task
project, ok := projects[wrapper.task.Project]
if !ok {
return fmt.Errorf("could not find project %v for task %v",
wrapper.task.Project, wrapper.task.Id)
}
// get the host for the task
host, err := host.FindOne(host.ById(wrapper.task.HostId))
if err != nil {
return fmt.Errorf("error finding host %v for task %v: %v",
wrapper.task.HostId, wrapper.task.Id, err)
}
// if there's no relevant host, something went wrong
if host == nil {
evergreen.Logger.Logf(slogger.ERROR, "no entry found for host %v", wrapper.task.HostId)
return wrapper.task.MarkUnscheduled()
}
// sanity check that the host is actually running the task
if host.RunningTask != wrapper.task.Id {
return fmt.Errorf("task %v says it is running on host %v, but the"+
" host thinks it is running task %v", wrapper.task.Id, host.Id,
host.RunningTask)
}
// take different action, depending on the type of task death
switch wrapper.reason {
case HeartbeatTimeout:
err = cleanUpTimedOutHeartbeat(wrapper.task, project, host)
default:
return fmt.Errorf("unknown reason for cleaning up task: %v", wrapper.reason)
}
if err != nil {
return fmt.Errorf("error cleaning up task %v: %v", wrapper.task.Id, err)
}
return nil
}
示例10: TestTaskEndEndpoint
func TestTaskEndEndpoint(t *testing.T) {
setupTlsConfigs(t)
for tlsString, tlsConfig := range tlsConfigs {
testTask, _, err := setupAPITestData(testConfig, "random", "linux-64", NoPatch, t)
testutil.HandleTestingErr(err, t, "Couldn't make test data: %v", err)
Convey("With a live api server, agent, and test task over "+tlsString, t, func() {
testServer, err := apiserver.CreateTestServer(testConfig, tlsConfig, plugin.APIPlugins, Verbose)
testutil.HandleTestingErr(err, t, "Couldn't create apiserver: %v", err)
testAgent, err := createAgent(testServer, testTask)
testutil.HandleTestingErr(err, t, "failed to create agent: %v")
testAgent.heartbeater.Interval = 10 * time.Second
testAgent.StartBackgroundActions(&NoopSignalHandler{})
Convey("calling end() should update task's/host's status properly "+
"and start running the next task", func() {
subsequentTaskId := testTask.Id + "Two"
details := &apimodels.TaskEndDetail{Status: evergreen.TaskSucceeded}
taskEndResp, err := testAgent.End(details)
time.Sleep(1 * time.Second)
So(err, ShouldBeNil)
taskUpdate, err := model.FindTask(testTask.Id)
So(err, ShouldBeNil)
So(taskUpdate.Status, ShouldEqual, evergreen.TaskSucceeded)
testHost, err := host.FindOne(host.ById(testTask.HostId))
So(err, ShouldBeNil)
So(testHost.RunningTask, ShouldEqual, subsequentTaskId)
taskUpdate, err = model.FindTask(subsequentTaskId)
So(err, ShouldBeNil)
So(taskUpdate.Status, ShouldEqual, evergreen.TaskDispatched)
So(taskEndResp, ShouldNotBeNil)
So(taskEndResp.RunNext, ShouldBeTrue)
So(taskEndResp.TaskId, ShouldEqual, subsequentTaskId)
})
})
}
}
示例11: taskFinished
// taskFinished constructs the appropriate response for each markEnd
// request the API server receives from an agent. The two possible responses are:
// 1. Inform the agent of another task to run
// 2. Inform the agent that it should terminate immediately
// The first case is the usual expected flow. The second case however, could
// occur for a number of reasons including:
// a. The version of the agent running on the remote machine is stale
// b. The host the agent is running on has been decommissioned
// c. There is no currently queued dispatchable and activated task
// In any of these aforementioned cases, the agent in question should terminate
// immediately and cease running any tasks on its host.
func (as *APIServer) taskFinished(w http.ResponseWriter, task *model.Task, finishTime time.Time) {
taskEndResponse := &apimodels.TaskEndResponse{}
// a. fetch the host this task just completed on to see if it's
// now decommissioned
host, err := host.FindOne(host.ById(task.HostId))
if err != nil {
message := fmt.Sprintf("Error locating host for task %v - set to %v: %v", task.Id,
task.HostId, err)
evergreen.Logger.Logf(slogger.ERROR, message)
taskEndResponse.Message = message
as.WriteJSON(w, http.StatusInternalServerError, taskEndResponse)
return
}
if host == nil {
message := fmt.Sprintf("Error finding host running for task %v - set to %v", task.Id,
task.HostId)
evergreen.Logger.Logf(slogger.ERROR, message)
taskEndResponse.Message = message
as.WriteJSON(w, http.StatusInternalServerError, taskEndResponse)
return
}
if host.Status == evergreen.HostDecommissioned || host.Status == evergreen.HostQuarantined {
markHostRunningTaskFinished(host, task, "")
message := fmt.Sprintf("Host %v - running %v - is in state '%v'. Agent will terminate",
task.HostId, task.Id, host.Status)
evergreen.Logger.Logf(slogger.INFO, message)
taskEndResponse.Message = message
as.WriteJSON(w, http.StatusOK, taskEndResponse)
return
}
// b. check if the agent needs to be rebuilt
taskRunnerInstance := taskrunner.NewTaskRunner(&as.Settings)
agentRevision, err := taskRunnerInstance.HostGateway.GetAgentRevision()
if err != nil {
markHostRunningTaskFinished(host, task, "")
evergreen.Logger.Logf(slogger.ERROR, "failed to get agent revision: %v", err)
taskEndResponse.Message = err.Error()
as.WriteJSON(w, http.StatusInternalServerError, taskEndResponse)
return
}
if host.AgentRevision != agentRevision {
markHostRunningTaskFinished(host, task, "")
message := fmt.Sprintf("Remote agent needs to be rebuilt")
evergreen.Logger.Logf(slogger.INFO, message)
taskEndResponse.Message = message
as.WriteJSON(w, http.StatusOK, taskEndResponse)
return
}
// c. fetch the task's distro queue to dispatch the next pending task
nextTask, err := getNextDistroTask(task, host)
if err != nil {
markHostRunningTaskFinished(host, task, "")
evergreen.Logger.Logf(slogger.ERROR, err.Error())
taskEndResponse.Message = err.Error()
as.WriteJSON(w, http.StatusOK, taskEndResponse)
return
}
if nextTask == nil {
markHostRunningTaskFinished(host, task, "")
taskEndResponse.Message = "No next task on queue"
} else {
taskEndResponse.Message = "Proceed with next task"
taskEndResponse.RunNext = true
taskEndResponse.TaskId = nextTask.Id
taskEndResponse.TaskSecret = nextTask.Secret
markHostRunningTaskFinished(host, task, nextTask.Id)
}
// give the agent the green light to keep churning
as.WriteJSON(w, http.StatusOK, taskEndResponse)
}
示例12: taskPage
//.........这里部分代码省略.........
}
if err != nil {
uis.LoggedError(w, r, http.StatusInternalServerError, fmt.Errorf("Error finding old task: %v", err))
return
}
}
projCtx.Task = taskFromDb
}
// Build a struct containing the subset of task data needed for display in the UI
task := uiTaskData{
Id: projCtx.Task.Id,
DisplayName: projCtx.Task.DisplayName,
Revision: projCtx.Task.Revision,
Status: projCtx.Task.Status,
TaskEndDetails: projCtx.Task.Details,
Distro: projCtx.Task.DistroId,
BuildVariant: projCtx.Task.BuildVariant,
BuildId: projCtx.Task.BuildId,
Activated: projCtx.Task.Activated,
Restarts: projCtx.Task.Restarts,
Execution: projCtx.Task.Execution,
Requester: projCtx.Task.Requester,
StartTime: projCtx.Task.StartTime.UnixNano(),
DispatchTime: projCtx.Task.DispatchTime.UnixNano(),
FinishTime: projCtx.Task.FinishTime.UnixNano(),
ExpectedDuration: projCtx.Task.ExpectedDuration,
PushTime: projCtx.Task.PushTime,
TimeTaken: projCtx.Task.TimeTaken,
Priority: projCtx.Task.Priority,
TestResults: projCtx.Task.TestResults,
Aborted: projCtx.Task.Aborted,
CurrentTime: time.Now().UnixNano(),
BuildVariantDisplay: projCtx.Build.DisplayName,
Message: projCtx.Version.Message,
Project: projCtx.Version.Identifier,
Author: projCtx.Version.Author,
AuthorEmail: projCtx.Version.AuthorEmail,
VersionId: projCtx.Version.Id,
RepoOwner: projCtx.ProjectRef.Owner,
Repo: projCtx.ProjectRef.Repo,
Archived: archived,
}
deps, taskWaiting, err := getTaskDependencies(projCtx.Task)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
task.DependsOn = deps
task.TaskWaiting = taskWaiting
// Activating and deactivating tasks should clear out the
// MinQueuePos but just in case, lets not show it if we shouldn't
if projCtx.Task.Status == evergreen.TaskUndispatched && projCtx.Task.Activated {
task.MinQueuePos = projCtx.Task.MinQueuePos
}
if projCtx.Task.HostId != "" {
task.HostDNS = projCtx.Task.HostId
task.HostId = projCtx.Task.HostId
taskHost, err := host.FindOne(host.ById(projCtx.Task.HostId))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if taskHost != nil {
task.HostDNS = taskHost.Host
}
}
if projCtx.Patch != nil {
taskOnBaseCommit, err := projCtx.Task.FindTaskOnBaseCommit()
if err != nil {
uis.LoggedError(w, r, http.StatusInternalServerError, err)
return
}
taskPatch := &uiPatch{Patch: *projCtx.Patch}
if taskOnBaseCommit != nil {
taskPatch.BaseTaskId = taskOnBaseCommit.Id
}
taskPatch.StatusDiffs = model.StatusDiffTasks(taskOnBaseCommit, projCtx.Task).Tests
task.PatchInfo = taskPatch
}
flashes := PopFlashes(uis.CookieStore, r, w)
pluginContext := projCtx.ToPluginContext(uis.Settings, GetUser(r))
pluginContent := getPluginDataAndHTML(uis, plugin.TaskPage, pluginContext)
uis.WriteHTML(w, http.StatusOK, struct {
ProjectData projectContext
User *user.DBUser
Flashes []interface{}
Task uiTaskData
PluginContent pluginData
}{projCtx, GetUser(r), flashes, task, pluginContent}, "base",
"task.html", "base_angular.html", "menu.html")
}
示例13: startEC2Instance
func startEC2Instance(ec2Handle *ec2.EC2, options *ec2.RunInstancesOptions,
intentHost *host.Host) (*host.Host, *ec2.RunInstancesResp, error) {
// start the instance
resp, err := ec2Handle.RunInstances(options)
if err != nil {
// remove the intent host document
rmErr := intentHost.Remove()
if rmErr != nil {
evergreen.Logger.Errorf(slogger.ERROR, "Could not remove intent host "+
"“%v”: %v", intentHost.Id, rmErr)
}
return nil, nil, evergreen.Logger.Errorf(slogger.ERROR,
"EC2 RunInstances API call returned error: %v", err)
}
evergreen.Logger.Logf(slogger.DEBUG, "Spawned %v instance", len(resp.Instances))
// the instance should have been successfully spawned
instance := resp.Instances[0]
evergreen.Logger.Logf(slogger.DEBUG, "Started %v", instance.InstanceId)
evergreen.Logger.Logf(slogger.DEBUG, "Key name: %v", string(options.KeyName))
// find old intent host
host, err := host.FindOne(host.ById(intentHost.Id))
if host == nil {
return nil, nil, evergreen.Logger.Errorf(slogger.ERROR, "Can't locate "+
"record inserted for intended host “%v”", intentHost.Id)
}
if err != nil {
return nil, nil, evergreen.Logger.Errorf(slogger.ERROR, "Can't locate "+
"record inserted for intended host “%v” due to error: %v",
intentHost.Id, err)
}
// we found the old document now we can insert the new one
host.Id = instance.InstanceId
err = host.Insert()
if err != nil {
return nil, nil, evergreen.Logger.Errorf(slogger.ERROR, "Could not insert "+
"updated host information for “%v” with “%v”: %v", intentHost.Id,
host.Id, err)
}
// remove the intent host document
err = intentHost.Remove()
if err != nil {
return nil, nil, evergreen.Logger.Errorf(slogger.ERROR, "Could not remove "+
"insert host “%v” (replaced by “%v”): %v", intentHost.Id, host.Id,
err)
}
var infoResp *ec2.DescribeInstancesResp
instanceInfoRetryCount := 0
instanceInfoMaxRetries := 5
for {
infoResp, err = ec2Handle.DescribeInstances([]string{instance.InstanceId}, nil)
if err != nil {
instanceInfoRetryCount++
if instanceInfoRetryCount == instanceInfoMaxRetries {
evergreen.Logger.Errorf(slogger.ERROR, "There was an error querying for the "+
"instance's information and retries are exhausted. The insance may "+
"be up.")
return nil, resp, err
}
evergreen.Logger.Errorf(slogger.DEBUG, "There was an error querying for the "+
"instance's information. Retrying in 30 seconds. Error: %v", err)
time.Sleep(30 * time.Second)
continue
}
break
}
reservations := infoResp.Reservations
if len(reservations) < 1 {
return nil, resp, fmt.Errorf("Reservation was returned as nil, you " +
"may have to check manually")
}
instancesInfo := reservations[0].Instances
if len(instancesInfo) < 1 {
return nil, resp, fmt.Errorf("Reservation appears to have no " +
"associated instances")
}
return host, resp, nil
}
示例14: SpawnInstance
//SpawnInstance creates a new droplet for the given distro.
func (digoMgr *DigitalOceanManager) SpawnInstance(d *distro.Distro, owner string, userHost bool) (*host.Host, error) {
if d.Provider != ProviderName {
return nil, fmt.Errorf("Can't spawn instance of %v for distro %v: provider is %v", ProviderName, d.Id, d.Provider)
}
digoSettings := &Settings{}
if err := mapstructure.Decode(d.ProviderSettings, digoSettings); err != nil {
return nil, fmt.Errorf("Error decoding params for distro %v: %v", d.Id, err)
}
if err := digoSettings.Validate(); err != nil {
return nil, fmt.Errorf("Invalid DigitalOcean settings in distro %v: %v", d.Id, err)
}
instanceName := "droplet-" +
fmt.Sprintf("%v", rand.New(rand.NewSource(time.Now().UnixNano())).Int())
intentHost := &host.Host{
Id: instanceName,
User: d.User,
Distro: *d,
Tag: instanceName,
CreationTime: time.Now(),
Status: evergreen.HostUninitialized,
TerminationTime: util.ZeroTime,
TaskDispatchTime: util.ZeroTime,
Provider: ProviderName,
StartedBy: owner,
}
dropletReq := &digo.Droplet{
SizeId: digoSettings.SizeId,
ImageId: digoSettings.ImageId,
RegionId: digoSettings.RegionId,
Name: instanceName,
SshKey: digoSettings.SSHKeyId,
}
if err := intentHost.Insert(); err != nil {
return nil, evergreen.Logger.Errorf(slogger.ERROR, "Could not insert intent "+
"host '%v': %v", intentHost.Id, err)
}
evergreen.Logger.Logf(slogger.DEBUG, "Successfully inserted intent host '%v' "+
"for distro '%v' to signal cloud instance spawn intent", instanceName,
d.Id)
newDroplet, err := digoMgr.account.CreateDroplet(dropletReq)
if err != nil {
evergreen.Logger.Logf(slogger.ERROR, "DigitalOcean create droplet API call failed"+
" for intent host '%v': %v", intentHost.Id, err)
// remove the intent host document
rmErr := intentHost.Remove()
if rmErr != nil {
return nil, evergreen.Logger.Errorf(slogger.ERROR, "Could not remove intent host "+
"'%v': %v", intentHost.Id, rmErr)
}
return nil, err
}
// find old intent host
host, err := host.FindOne(host.ById(intentHost.Id))
if host == nil {
return nil, evergreen.Logger.Errorf(slogger.ERROR, "Can't locate "+
"record inserted for intended host “%v”", intentHost.Id)
}
if err != nil {
return nil, evergreen.Logger.Errorf(slogger.ERROR, "Failed to look up intent host %v: %v",
intentHost.Id, err)
}
host.Id = fmt.Sprintf("%v", newDroplet.Id)
host.Host = newDroplet.IpAddress
err = host.Insert()
if err != nil {
return nil, evergreen.Logger.Errorf(slogger.ERROR, "Failed to insert new host %v"+
"for intent host %v: %v", host.Id, intentHost.Id, err)
}
// remove the intent host document
err = intentHost.Remove()
if err != nil {
return nil, evergreen.Logger.Errorf(slogger.ERROR, "Could not remove "+
"insert host “%v” (replaced by “%v”): %v", intentHost.Id, host.Id,
err)
}
return host, nil
}
示例15: TestWarnSlowProvisioningHosts
func TestWarnSlowProvisioningHosts(t *testing.T) {
testConfig := evergreen.TestConfig()
db.SetGlobalSessionProvider(db.SessionFactoryFromConfig(testConfig))
Convey("When building warnings for hosts that are taking a long time to"+
" provision", t, func() {
// reset the db
testutil.HandleTestingErr(db.ClearCollections(host.Collection),
t, "error clearing hosts collection")
Convey("hosts that have not hit the threshold should not trigger a"+
" warning", func() {
host1 := &host.Host{
Id: "h1",
StartedBy: evergreen.User,
CreationTime: time.Now().Add(-10 * time.Minute),
}
testutil.HandleTestingErr(host1.Insert(), t, "error inserting host")
warnings, err := slowProvisioningWarnings(testConfig)
So(err, ShouldBeNil)
So(len(warnings), ShouldEqual, 0)
})
Convey("hosts that have already triggered a notification should not"+
" trigger another", func() {
host1 := &host.Host{
Id: "h1",
StartedBy: evergreen.User,
CreationTime: time.Now().Add(-1 * time.Hour),
Notifications: map[string]bool{
slowProvisioningWarning: true,
},
}
testutil.HandleTestingErr(host1.Insert(), t, "error inserting host")
warnings, err := slowProvisioningWarnings(testConfig)
So(err, ShouldBeNil)
So(len(warnings), ShouldEqual, 0)
})
Convey("terminated hosts should not trigger a warning", func() {
host1 := &host.Host{
Id: "h1",
StartedBy: evergreen.User,
Status: evergreen.HostTerminated,
CreationTime: time.Now().Add(-1 * time.Hour),
}
testutil.HandleTestingErr(host1.Insert(), t, "error inserting host")
warnings, err := slowProvisioningWarnings(testConfig)
So(err, ShouldBeNil)
So(len(warnings), ShouldEqual, 0)
})
Convey("hosts that are at the threshold and have not previously"+
" triggered a warning should trigger one", func() {
host1 := &host.Host{
Id: "h1",
StartedBy: evergreen.User,
CreationTime: time.Now().Add(-1 * time.Hour),
}
testutil.HandleTestingErr(host1.Insert(), t, "error inserting host")
warnings, err := slowProvisioningWarnings(testConfig)
So(err, ShouldBeNil)
So(len(warnings), ShouldEqual, 1)
// make sure running the callback sets the notification key
So(warnings[0].callback(warnings[0].host, warnings[0].threshold), ShouldBeNil)
host1, err = host.FindOne(host.ById("h1"))
So(err, ShouldBeNil)
So(host1.Notifications[slowProvisioningWarning], ShouldBeTrue)
})
})
}