本文整理匯總了Golang中bosh/handler.NewValueResponse函數的典型用法代碼示例。如果您正苦於以下問題:Golang NewValueResponse函數的具體用法?Golang NewValueResponse怎麽用?Golang NewValueResponse使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了NewValueResponse函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: Dispatch
func (dispatcher concreteActionDispatcher) Dispatch(req boshhandler.Request) (resp boshhandler.Response) {
action, err := dispatcher.actionFactory.Create(req.Method)
switch {
case err != nil:
resp = boshhandler.NewExceptionResponse("unknown message %s", req.Method)
dispatcher.logger.Error("Action Dispatcher", "Unknown action %s", req.Method)
case action.IsAsynchronous():
task := dispatcher.taskService.StartTask(func() (value interface{}, err error) {
value, err = dispatcher.actionRunner.Run(action, req.GetPayload())
return
})
resp = boshhandler.NewValueResponse(boshtask.TaskStateValue{
AgentTaskId: task.Id,
State: task.State,
})
default:
value, err := dispatcher.actionRunner.Run(action, req.GetPayload())
if err != nil {
err = bosherr.WrapError(err, "Action Failed %s", req.Method)
resp = boshhandler.NewExceptionResponse(err.Error())
dispatcher.logger.Error("Action Dispatcher", err.Error())
return
}
resp = boshhandler.NewValueResponse(value)
}
return
}
示例2: statusHandler
func (d *dummyNatsJobSupervisor) statusHandler(req boshhandler.Request) boshhandler.Response {
switch req.Method {
case "set_dummy_status":
// Do not unmarshal message until determining its method
var body map[string]string
err := json.Unmarshal(req.GetPayload(), &body)
if err != nil {
return boshhandler.NewExceptionResponse(err.Error())
}
d.status = body["status"]
if d.status == "failing" && d.jobFailureHandler != nil {
d.jobFailureHandler(boshalert.MonitAlert{
ID: "fake-monit-alert",
Service: "fake-monit-service",
Event: "failing",
Action: "start",
Date: "Sun, 22 May 2011 20:07:41 +0500",
Description: "fake-monit-description",
})
}
return boshhandler.NewValueResponse("ok")
default:
return nil
}
}
示例3: init
func init() {
Describe("Testing with Ginkgo", func() {
It("run sets the dispatcher as message handler", func() {
deps, agent := buildAgent()
deps.actionDispatcher.DispatchResp = boshhandler.NewValueResponse("pong")
err := agent.Run()
assert.NoError(GinkgoT(), err)
assert.True(GinkgoT(), deps.handler.ReceivedRun)
req := boshhandler.NewRequest("reply to me!", "some action", []byte("some payload"))
resp := deps.handler.Func(req)
assert.Equal(GinkgoT(), deps.actionDispatcher.DispatchReq, req)
assert.Equal(GinkgoT(), resp, deps.actionDispatcher.DispatchResp)
})
It("run sets up heartbeats", func() {
deps, agent := buildAgent()
deps.platform.FakeVitalsService.GetVitals = boshvitals.Vitals{
Load: []string{"a", "b", "c"},
}
err := agent.Run()
assert.NoError(GinkgoT(), err)
assert.False(GinkgoT(), deps.handler.TickHeartbeatsSent)
assert.True(GinkgoT(), deps.handler.InitialHeartbeatSent)
assert.Equal(GinkgoT(), "heartbeat", deps.handler.SendToHealthManagerTopic)
time.Sleep(5 * time.Millisecond)
assert.True(GinkgoT(), deps.handler.TickHeartbeatsSent)
hb := deps.handler.SendToHealthManagerPayload.(boshmbus.Heartbeat)
assert.Equal(GinkgoT(), deps.platform.FakeVitalsService.GetVitals, hb.Vitals)
})
It("run sets the callback for job failures monitoring", func() {
deps, agent := buildAgent()
builtAlert := boshalert.Alert{Id: "some built alert id"}
deps.alertBuilder.BuildAlert = builtAlert
err := agent.Run()
assert.NoError(GinkgoT(), err)
assert.NotEqual(GinkgoT(), deps.handler.SendToHealthManagerTopic, "alert")
failureAlert := boshalert.MonitAlert{Id: "some random id"}
deps.jobSupervisor.OnJobFailure(failureAlert)
assert.Equal(GinkgoT(), deps.alertBuilder.BuildInput, failureAlert)
assert.Equal(GinkgoT(), deps.handler.SendToHealthManagerTopic, "alert")
assert.Equal(GinkgoT(), deps.handler.SendToHealthManagerPayload, builtAlert)
})
})
}
示例4: dispatchAsynchronousAction
func (dispatcher concreteActionDispatcher) dispatchAsynchronousAction(
action boshaction.Action,
req boshhandler.Request,
) boshhandler.Response {
dispatcher.logger.Info(actionDispatcherLogTag, "Running async action %s", req.Method)
var task boshtask.Task
var err error
runTask := func() (interface{}, error) {
return dispatcher.actionRunner.Run(action, req.GetPayload())
}
cancelTask := func(_ boshtask.Task) error { return action.Cancel() }
// Certain long-running tasks (e.g. configure_networks) must be resumed
// after agent restart so that API consumers do not need to know
// if agent is restarted midway through the task.
if action.IsPersistent() {
dispatcher.logger.Info(actionDispatcherLogTag, "Running persistent action %s", req.Method)
task, err = dispatcher.taskService.CreateTask(runTask, cancelTask, dispatcher.removeTaskInfo)
if err != nil {
err = bosherr.WrapError(err, "Create Task Failed %s", req.Method)
dispatcher.logger.Error(actionDispatcherLogTag, err.Error())
return boshhandler.NewExceptionResponse(err)
}
taskInfo := boshtask.TaskInfo{
TaskID: task.ID,
Method: req.Method,
Payload: req.GetPayload(),
}
err = dispatcher.taskManager.AddTaskInfo(taskInfo)
if err != nil {
err = bosherr.WrapError(err, "Action Failed %s", req.Method)
dispatcher.logger.Error(actionDispatcherLogTag, err.Error())
return boshhandler.NewExceptionResponse(err)
}
} else {
task, err = dispatcher.taskService.CreateTask(runTask, cancelTask, nil)
if err != nil {
err = bosherr.WrapError(err, "Create Task Failed %s", req.Method)
dispatcher.logger.Error(actionDispatcherLogTag, err.Error())
return boshhandler.NewExceptionResponse(err)
}
}
dispatcher.taskService.StartTask(task)
return boshhandler.NewValueResponse(boshtask.TaskStateValue{
AgentTaskID: task.ID,
State: task.State,
})
}
示例5: startServer
func startServer() (serverURL string, handler HttpsHandler, fs *fakesys.FakeFileSystem) {
serverURL = "https://user:[email protected]:6900"
mbusUrl, _ := url.Parse(serverURL)
logger := boshlog.NewLogger(boshlog.LEVEL_NONE)
fs = fakesys.NewFakeFileSystem()
dirProvider := boshdir.NewDirectoriesProvider("/var/vcap")
handler = NewHttpsHandler(mbusUrl, logger, fs, dirProvider)
go handler.Start(func(req boshhandler.Request) (resp boshhandler.Response) {
receivedRequest = req
return boshhandler.NewValueResponse("expected value")
})
return
}
示例6: dispatchSynchronousAction
func (dispatcher concreteActionDispatcher) dispatchSynchronousAction(
action boshaction.Action,
req boshhandler.Request,
) boshhandler.Response {
dispatcher.logger.Info(actionDispatcherLogTag, "Running sync action %s", req.Method)
value, err := dispatcher.actionRunner.Run(action, req.GetPayload())
if err != nil {
err = bosherr.WrapError(err, "Action Failed %s", req.Method)
dispatcher.logger.Error(actionDispatcherLogTag, err.Error())
return boshhandler.NewExceptionResponse(err)
}
return boshhandler.NewValueResponse(value)
}
示例7: TestRunSetsTheDispatcherAsMessageHandler
func TestRunSetsTheDispatcherAsMessageHandler(t *testing.T) {
deps, agent := buildAgent()
deps.actionDispatcher.DispatchResp = boshhandler.NewValueResponse("pong")
err := agent.Run()
assert.NoError(t, err)
assert.True(t, deps.handler.ReceivedRun)
req := boshhandler.NewRequest("reply to me!", "some action", []byte("some payload"))
resp := deps.handler.Func(req)
assert.Equal(t, deps.actionDispatcher.DispatchReq, req)
assert.Equal(t, resp, deps.actionDispatcher.DispatchResp)
}
示例8: TestNatsHandlerStart
func TestNatsHandlerStart(t *testing.T) {
settings := &fakesettings.FakeSettingsService{
AgentId: "my-agent-id",
MbusUrl: "nats://foo:[email protected]:1234",
}
client, handler := buildNatsClientAndHandler(settings)
var receivedRequest boshhandler.Request
handler.Start(func(req boshhandler.Request) (resp boshhandler.Response) {
receivedRequest = req
return boshhandler.NewValueResponse("expected value")
})
defer handler.Stop()
// check connection
assert.NotNil(t, client.ConnectedConnectionProvider)
// check subscriptions
assert.Equal(t, len(client.Subscriptions), 1)
subscriptions := client.Subscriptions["agent.my-agent-id"]
assert.Equal(t, len(subscriptions), 1)
// test subscription callback
expectedPayload := []byte(`{"method":"ping","arguments":["foo","bar"], "reply_to": "reply to me!"}`)
subscription := client.Subscriptions["agent.my-agent-id"][0]
subscription.Callback(&yagnats.Message{
Subject: "agent.my-agent-id",
Payload: expectedPayload,
})
// request received
assert.Equal(t, receivedRequest, boshhandler.Request{
ReplyTo: "reply to me!",
Method: "ping",
Payload: expectedPayload,
})
// response sent
assert.Equal(t, len(client.PublishedMessages), 1)
messages := client.PublishedMessages["reply to me!"]
assert.Equal(t, len(messages), 1)
message := messages[0]
assert.Equal(t, []byte(`{"value":"expected value"}`), message.Payload)
}
示例9: TestDispatchHandlesSynchronousAction
func TestDispatchHandlesSynchronousAction(t *testing.T) {
logger, taskService, actionFactory, actionRunner := getActionDispatcherDependencies()
// when action is successful
actionFactory.CreateAction = &fakeaction.TestAction{
Asynchronous: false,
}
actionRunner.RunValue = "some value"
dispatcher := NewActionDispatcher(logger, taskService, actionFactory, actionRunner)
req := boshhandler.NewRequest("reply to me!", "some action", []byte("some payload"))
resp := dispatcher.Dispatch(req)
assert.Equal(t, req.Method, actionFactory.CreateMethod)
assert.Equal(t, req.GetPayload(), actionRunner.RunPayload)
assert.Equal(t, boshhandler.NewValueResponse("some value"), resp)
}
示例10: init
func init() {
Describe("Agent", func() {
var (
agent Agent
logger boshlog.Logger
handler *fakembus.FakeHandler
platform *fakeplatform.FakePlatform
actionDispatcher *FakeActionDispatcher
alertBuilder *fakealert.FakeAlertBuilder
alertSender AlertSender
jobSupervisor *fakejobsuper.FakeJobSupervisor
specService *fakeas.FakeV1Service
)
BeforeEach(func() {
logger = boshlog.NewLogger(boshlog.LevelDebug)
handler = &fakembus.FakeHandler{}
platform = fakeplatform.NewFakePlatform()
actionDispatcher = &FakeActionDispatcher{}
alertBuilder = fakealert.NewFakeAlertBuilder()
alertSender = NewAlertSender(handler, alertBuilder)
jobSupervisor = fakejobsuper.NewFakeJobSupervisor()
specService = fakeas.NewFakeV1Service()
agent = New(logger, handler, platform, actionDispatcher, alertSender, jobSupervisor, specService, 5*time.Millisecond)
})
Describe("Run", func() {
It("lets dispatcher handle requests arriving via handler", func() {
err := agent.Run()
Expect(err).ToNot(HaveOccurred())
expectedResp := boshhandler.NewValueResponse("pong")
actionDispatcher.DispatchResp = expectedResp
req := boshhandler.NewRequest("fake-reply", "fake-action", []byte("fake-payload"))
resp := handler.RunFunc(req)
Expect(actionDispatcher.DispatchReq).To(Equal(req))
Expect(resp).To(Equal(expectedResp))
})
It("resumes persistent actions *before* dispatching new requests", func() {
resumedBeforeStartingToDispatch := false
handler.RunCallBack = func() {
resumedBeforeStartingToDispatch = actionDispatcher.ResumedPreviouslyDispatchedTasks
}
err := agent.Run()
Expect(err).ToNot(HaveOccurred())
Expect(resumedBeforeStartingToDispatch).To(BeTrue())
})
Context("when heartbeats can be sent", func() {
BeforeEach(func() {
handler.KeepOnRunning()
})
BeforeEach(func() {
jobName := "fake-job"
jobIndex := 1
specService.Spec = boshas.V1ApplySpec{
JobSpec: boshas.JobSpec{Name: &jobName},
Index: &jobIndex,
}
jobSupervisor.StatusStatus = "fake-state"
platform.FakeVitalsService.GetVitals = boshvitals.Vitals{
Load: []string{"a", "b", "c"},
}
})
expectedJobName := "fake-job"
expectedJobIndex := 1
expectedHb := boshmbus.Heartbeat{
Job: &expectedJobName,
Index: &expectedJobIndex,
JobState: "fake-state",
Vitals: boshvitals.Vitals{Load: []string{"a", "b", "c"}},
}
It("sends initial heartbeat", func() {
// Configure periodic heartbeat every 5 hours
// so that we are sure that we will not receive it
agent = New(logger, handler, platform, actionDispatcher, alertSender, jobSupervisor, specService, 5*time.Hour)
// Immediately exit after sending initial heartbeat
handler.SendToHealthManagerErr = errors.New("stop")
err := agent.Run()
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("stop"))
Expect(handler.HMRequests()).To(Equal([]fakembus.HMRequest{
fakembus.HMRequest{Topic: "heartbeat", Payload: expectedHb},
}))
})
It("sends periodic heartbeats", func() {
sentRequests := 0
//.........這裏部分代碼省略.........
示例11:
fs *fakesys.FakeFileSystem
receivedRequest boshhandler.Request
httpClient http.Client
)
BeforeEach(func() {
serverURL = "https://user:[email protected]:6900"
mbusURL, _ := url.Parse(serverURL)
logger := boshlog.NewLogger(boshlog.LevelNone)
fs = fakesys.NewFakeFileSystem()
dirProvider := boshdir.NewDirectoriesProvider("/var/vcap")
handler = NewHTTPSHandler(mbusURL, logger, fs, dirProvider)
go handler.Start(func(req boshhandler.Request) (resp boshhandler.Response) {
receivedRequest = req
return boshhandler.NewValueResponse("expected value")
})
httpTransport := &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}
httpClient = http.Client{Transport: httpTransport}
})
AfterEach(func() {
handler.Stop()
time.Sleep(1 * time.Millisecond)
})
Describe("POST /agent", func() {
It("receives request and responds", func() {
postBody := `{"method":"ping","arguments":["foo","bar"], "reply_to": "reply to me!"}`
postPayload := strings.NewReader(postBody)
示例12: init
func init() {
Describe("Testing with Ginkgo", func() {
It("nats handler start", func() {
settings := &fakesettings.FakeSettingsService{
AgentId: "my-agent-id",
MbusUrl: "nats://foo:[email protected]:1234",
}
client, handler := buildNatsClientAndHandler(settings)
var receivedRequest boshhandler.Request
handler.Start(func(req boshhandler.Request) (resp boshhandler.Response) {
receivedRequest = req
return boshhandler.NewValueResponse("expected value")
})
defer handler.Stop()
Expect(client.ConnectedConnectionProvider).ToNot(BeNil())
Expect(len(client.Subscriptions)).To(Equal(1))
subscriptions := client.Subscriptions["agent.my-agent-id"]
Expect(len(subscriptions)).To(Equal(1))
expectedPayload := []byte(`{"method":"ping","arguments":["foo","bar"], "reply_to": "reply to me!"}`)
subscription := client.Subscriptions["agent.my-agent-id"][0]
subscription.Callback(&yagnats.Message{
Subject: "agent.my-agent-id",
Payload: expectedPayload,
})
assert.Equal(GinkgoT(), receivedRequest, boshhandler.Request{
ReplyTo: "reply to me!",
Method: "ping",
Payload: expectedPayload,
})
Expect(len(client.PublishedMessages)).To(Equal(1))
messages := client.PublishedMessages["reply to me!"]
Expect(len(messages)).To(Equal(1))
message := messages[0]
Expect([]byte(`{"value":"expected value"}`)).To(Equal(message.Payload))
})
It("nats send periodic heartbeat", func() {
settings := &fakesettings.FakeSettingsService{
AgentId: "my-agent-id",
MbusUrl: "nats://foo:[email protected]:1234",
}
client, handler := buildNatsClientAndHandler(settings)
errChan := make(chan error, 1)
jobName := "foo"
jobIndex := 0
expectedHeartbeat := Heartbeat{Job: &jobName, Index: &jobIndex}
go func() {
errChan <- handler.SendToHealthManager("heartbeat", expectedHeartbeat)
}()
var err error
select {
case err = <-errChan:
}
Expect(err).ToNot(HaveOccurred())
Expect(len(client.PublishedMessages)).To(Equal(1))
messages := client.PublishedMessages["hm.agent.heartbeat.my-agent-id"]
Expect(len(messages)).To(Equal(1))
message := messages[0]
expectedJson, _ := json.Marshal(expectedHeartbeat)
Expect(string(expectedJson)).To(Equal(string(message.Payload)))
})
It("nats handler connection info", func() {
settings := &fakesettings.FakeSettingsService{MbusUrl: "nats://foo:[email protected]:1234"}
client, handler := buildNatsClientAndHandler(settings)
err := handler.Start(func(req boshhandler.Request) (res boshhandler.Response) { return })
Expect(err).ToNot(HaveOccurred())
defer handler.Stop()
Expect(client.ConnectedConnectionProvider).ToNot(BeNil())
connInfo := client.ConnectedConnectionProvider
expectedConnInfo := &yagnats.ConnectionInfo{
Addr: "127.0.0.1:1234",
Username: "foo",
Password: "bar",
}
Expect(connInfo).To(Equal(expectedConnInfo))
})
It("nats handler connection info does not err when no username and password", func() {
//.........這裏部分代碼省略.........
示例13: init
func init() {
Describe("Testing with Ginkgo", func() {
It("dispatch responds with exception when the method is unknown", func() {
logger, taskService, actionFactory, actionRunner := getActionDispatcherDependencies()
req := boshhandler.NewRequest("reply to me", "gibberish", []byte{})
actionFactory.CreateErr = true
dispatcher := NewActionDispatcher(logger, taskService, actionFactory, actionRunner)
resp := dispatcher.Dispatch(req)
boshassert.MatchesJsonString(GinkgoT(), resp, `{"exception":{"message":"unknown message gibberish"}}`)
assert.Equal(GinkgoT(), actionFactory.CreateMethod, "gibberish")
})
It("dispatch handles synchronous action", func() {
logger, taskService, actionFactory, actionRunner := getActionDispatcherDependencies()
actionFactory.CreateAction = &fakeaction.TestAction{
Asynchronous: false,
}
actionRunner.RunValue = "some value"
dispatcher := NewActionDispatcher(logger, taskService, actionFactory, actionRunner)
req := boshhandler.NewRequest("reply to me!", "some action", []byte("some payload"))
resp := dispatcher.Dispatch(req)
assert.Equal(GinkgoT(), req.Method, actionFactory.CreateMethod)
assert.Equal(GinkgoT(), req.GetPayload(), actionRunner.RunPayload)
assert.Equal(GinkgoT(), boshhandler.NewValueResponse("some value"), resp)
})
It("dispatch handles synchronous action when err", func() {
logger, taskService, actionFactory, actionRunner := getActionDispatcherDependencies()
actionFactory.CreateAction = &fakeaction.TestAction{}
actionRunner.RunErr = errors.New("some error")
dispatcher := NewActionDispatcher(logger, taskService, actionFactory, actionRunner)
req := boshhandler.NewRequest("reply to me!", "some action", []byte("some payload"))
resp := dispatcher.Dispatch(req)
expectedJson := fmt.Sprintf("{\"exception\":{\"message\":\"Action Failed %s: some error\"}}", req.Method)
boshassert.MatchesJsonString(GinkgoT(), resp, expectedJson)
assert.Equal(GinkgoT(), actionFactory.CreateMethod, "some action")
})
It("dispatch handles asynchronous action", func() {
logger, taskService, actionFactory, actionRunner := getActionDispatcherDependencies()
taskService.StartTaskStartedTask = boshtask.Task{Id: "found-57-id", State: boshtask.TaskStateDone}
actionFactory.CreateAction = &fakeaction.TestAction{
Asynchronous: true,
}
actionRunner.RunValue = "some-task-result-value"
dispatcher := NewActionDispatcher(logger, taskService, actionFactory, actionRunner)
req := boshhandler.NewRequest("reply to me!", "some async action", []byte("some payload"))
resp := dispatcher.Dispatch(req)
boshassert.MatchesJsonString(GinkgoT(), resp, `{"value":{"agent_task_id":"found-57-id","state":"done"}}`)
value, err := taskService.StartTaskFunc()
assert.NoError(GinkgoT(), err)
assert.Equal(GinkgoT(), "some-task-result-value", value)
assert.Equal(GinkgoT(), req.Method, actionFactory.CreateMethod)
assert.Equal(GinkgoT(), req.GetPayload(), actionRunner.RunPayload)
assert.Equal(GinkgoT(), actionFactory.CreateMethod, "some async action")
})
})
}
示例14: init
func init() {
Describe("Agent", func() {
var (
agent Agent
logger boshlog.Logger
handler *fakembus.FakeHandler
platform *fakeplatform.FakePlatform
actionDispatcher *FakeActionDispatcher
alertBuilder *fakealert.FakeAlertBuilder
jobSupervisor *fakejobsuper.FakeJobSupervisor
specService *fakeas.FakeV1Service
)
BeforeEach(func() {
logger = boshlog.NewLogger(boshlog.LEVEL_NONE)
handler = &fakembus.FakeHandler{}
platform = fakeplatform.NewFakePlatform()
actionDispatcher = &FakeActionDispatcher{}
alertBuilder = fakealert.NewFakeAlertBuilder()
jobSupervisor = fakejobsuper.NewFakeJobSupervisor()
specService = fakeas.NewFakeV1Service()
agent = New(logger, handler, platform, actionDispatcher, alertBuilder, jobSupervisor, specService, 5*time.Millisecond)
})
Describe("Run", func() {
It("sets the dispatcher as message handler", func() {
actionDispatcher.DispatchResp = boshhandler.NewValueResponse("pong")
err := agent.Run()
Expect(err).ToNot(HaveOccurred())
Expect(handler.ReceivedRun).To(BeTrue())
req := boshhandler.NewRequest("fake-reply", "fake-action", []byte("fake-payload"))
resp := handler.Func(req)
Expect(req).To(Equal(actionDispatcher.DispatchReq))
Expect(actionDispatcher.DispatchResp).To(Equal(resp))
})
It("resumes persistent actions *before* dispatching new requests", func() {
resumedBefore := false
handler.RunFunc = func() {
resumedBefore = actionDispatcher.ResumedPreviouslyDispatchedTasks
}
err := agent.Run()
Expect(err).ToNot(HaveOccurred())
Expect(resumedBefore).To(BeTrue())
})
Context("when heartbeats can be sent", func() {
BeforeEach(func() {
jobName := "fake-job"
jobIndex := 1
specService.Spec = boshas.V1ApplySpec{
JobSpec: boshas.JobSpec{Name: &jobName},
Index: &jobIndex,
}
jobSupervisor.StatusStatus = "fake-state"
platform.FakeVitalsService.GetVitals = boshvitals.Vitals{
Load: []string{"a", "b", "c"},
}
})
expectedJobName := "fake-job"
expectedJobIndex := 1
expectedHb := boshmbus.Heartbeat{
Job: &expectedJobName,
Index: &expectedJobIndex,
JobState: "fake-state",
Vitals: boshvitals.Vitals{Load: []string{"a", "b", "c"}},
}
It("sends initial heartbeat", func() {
err := agent.Run()
Expect(err).ToNot(HaveOccurred())
Expect(handler.InitialHeartbeatSent).To(BeTrue())
Expect(handler.TickHeartbeatsSent).To(BeFalse())
Expect(handler.SendToHealthManagerTopic).To(Equal("heartbeat"))
Expect(handler.SendToHealthManagerPayload.(boshmbus.Heartbeat)).To(Equal(expectedHb))
})
It("sends periodic heartbeats", func() {
err := agent.Run()
Expect(err).ToNot(HaveOccurred())
Expect(handler.TickHeartbeatsSent).To(BeFalse())
time.Sleep(5 * time.Millisecond)
Expect(handler.TickHeartbeatsSent).To(BeTrue())
Expect(handler.SendToHealthManagerTopic).To(Equal("heartbeat"))
Expect(handler.SendToHealthManagerPayload.(boshmbus.Heartbeat)).To(Equal(expectedHb))
})
})
//.........這裏部分代碼省略.........
示例15: Dispatch
func (dispatcher concreteActionDispatcher) Dispatch(req boshhandler.Request) boshhandler.Response {
action, err := dispatcher.actionFactory.Create(req.Method)
switch {
case err != nil:
dispatcher.logger.Error("Action Dispatcher", "Unknown action %s", req.Method)
return boshhandler.NewExceptionResponse("unknown message %s", req.Method)
case action.IsAsynchronous():
dispatcher.logger.Error("Action Dispatcher", "Running async action %s", req.Method)
var task boshtask.Task
runTask := func() (interface{}, error) {
return dispatcher.actionRunner.Run(action, req.GetPayload())
}
// Certain long-running tasks (e.g. configure_networks) must be resumed
// after agent restart so that API consumers do not need to know
// if agent is restarted midway through the task.
if action.IsPersistent() {
dispatcher.logger.Error("Action Dispatcher", "Running persistent action %s", req.Method)
task, err = dispatcher.taskService.CreateTask(runTask, dispatcher.removeTaskInfo)
if err != nil {
err = bosherr.WrapError(err, "Create Task Failed %s", req.Method)
dispatcher.logger.Error("Action Dispatcher", err.Error())
return boshhandler.NewExceptionResponse(err.Error())
}
taskInfo := boshtask.TaskInfo{
TaskId: task.Id,
Method: req.Method,
Payload: req.GetPayload(),
}
err = dispatcher.taskManager.AddTaskInfo(taskInfo)
if err != nil {
err = bosherr.WrapError(err, "Action Failed %s", req.Method)
dispatcher.logger.Error("Action Dispatcher", err.Error())
return boshhandler.NewExceptionResponse(err.Error())
}
} else {
task, err = dispatcher.taskService.CreateTask(runTask, nil)
if err != nil {
err = bosherr.WrapError(err, "Create Task Failed %s", req.Method)
dispatcher.logger.Error("Action Dispatcher", err.Error())
return boshhandler.NewExceptionResponse(err.Error())
}
}
dispatcher.taskService.StartTask(task)
return boshhandler.NewValueResponse(boshtask.TaskStateValue{
AgentTaskId: task.Id,
State: task.State,
})
default:
dispatcher.logger.Debug("Action Dispatcher", "Running sync action %s", req.Method)
value, err := dispatcher.actionRunner.Run(action, req.GetPayload())
if err != nil {
err = bosherr.WrapError(err, "Action Failed %s", req.Method)
dispatcher.logger.Error("Action Dispatcher", err.Error())
return boshhandler.NewExceptionResponse(err.Error())
}
return boshhandler.NewValueResponse(value)
}
}