-
Notifications
You must be signed in to change notification settings - Fork 1
/
worker.go
213 lines (191 loc) · 6.13 KB
/
worker.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
/**
* Copyright 2017 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ------------------------------------------------------------------------------
*/
package processor
import (
"fmt"
"github.com/golang/protobuf/proto"
zmq "github.com/pebbe/zmq4"
"github.com/rberg2/sawtooth-go-sdk/messaging"
"github.com/rberg2/sawtooth-go-sdk/protobuf/processor_pb2"
"github.com/rberg2/sawtooth-go-sdk/protobuf/transaction_pb2"
"github.com/rberg2/sawtooth-go-sdk/protobuf/validator_pb2"
)
// The main worker thread finds an appropriate handler and processes the request
func worker(context *zmq.Context, uri string, queue chan *validator_pb2.Message, handlers []TransactionHandler) {
// Connect to the main send/receive thread
connection, err := messaging.NewConnection(context, zmq.DEALER, uri)
if err != nil {
logger.Errorf("Failed to connect to main thread: %v", err)
return
}
defer connection.Close()
id := connection.Identity()
// Receive work off of the queue until the queue is closed
for msg := range queue {
request := &processor_pb2.TpProcessRequest{}
err = proto.Unmarshal(msg.GetContent(), request)
if err != nil {
logger.Errorf(
"(%v) Failed to unmarshal TpProcessRequest: %v", id, err,
)
break
}
header := request.GetHeader()
// Try to find a handler
handler, err := findHandler(handlers, header)
if err != nil {
logger.Errorf("(%v) Failed to find handler: %v", id, err)
break
}
// Construct a new Context instance for the handler
contextId := request.GetContextId()
context := NewContext(connection, contextId)
// Run the handler
err = handler.Apply(request, context)
// Process the handler response
response := &processor_pb2.TpProcessResponse{}
if err != nil {
switch e := err.(type) {
case *InvalidTransactionError:
logger.Warnf("(%v) %v", id, e)
response.Status = processor_pb2.TpProcessResponse_INVALID_TRANSACTION
response.Message = e.Msg
response.ExtendedData = e.ExtendedData
case *InternalError:
logger.Warnf("(%v) %v", id, e)
response.Status = processor_pb2.TpProcessResponse_INTERNAL_ERROR
response.Message = e.Msg
response.ExtendedData = e.ExtendedData
case *AuthorizationException:
logger.Warnf("(%v) %v", id, e)
response.Status = processor_pb2.TpProcessResponse_INVALID_TRANSACTION
response.Message = e.Msg
response.ExtendedData = e.ExtendedData
default:
logger.Errorf("(%v) Unknown error: %v", id, err)
response.Status = processor_pb2.TpProcessResponse_INTERNAL_ERROR
response.Message = e.Error()
}
} else {
response.Status = processor_pb2.TpProcessResponse_OK
}
responseData, err := proto.Marshal(response)
if err != nil {
logger.Errorf("(%v) Failed to marshal TpProcessResponse: %v", id, err)
break
}
// Send back a response to the validator
err = connection.SendMsg(
validator_pb2.Message_TP_PROCESS_RESPONSE,
responseData, msg.GetCorrelationId(),
)
if err != nil {
logger.Errorf("(%v) Error sending TpProcessResponse: %v", id, err)
break
}
}
// Queue has closed, so send shutdown signal
logger.Infof("(%v) No more work in queue, shutting down", id)
err = connection.SendMsg(
validator_pb2.Message_DEFAULT,
[]byte{byte(0)}, "shutdown",
)
if err != nil {
logger.Errorf("(%v) Error sending shutdown: %v", id, err)
}
}
// Searches for and returns a handler that matches the header. If a suitable
// handler is not found, returns an error.
func findHandler(handlers []TransactionHandler, header *transaction_pb2.TransactionHeader) (TransactionHandler, error) {
for _, handler := range handlers {
if header.GetFamilyName() != handler.FamilyName() {
break
}
HeaderVersion := header.GetFamilyVersion()
HasVersion := false
for _, version := range handler.FamilyVersions() {
if version == HeaderVersion {
HasVersion = true
break
}
}
if !HasVersion {
break
}
return handler, nil
}
return nil, fmt.Errorf(
"Unknown handler: (%v, %v)", header.GetFamilyName(),
header.GetFamilyVersion(),
)
}
// Waits for something to come along a channel and then initiates processor shutdown
func shutdown(context *zmq.Context, uri string, queue chan *validator_pb2.Message, wait chan bool) {
// Wait for a request to shutdown
connection, err := messaging.NewConnection(context, zmq.DEALER, uri)
if err != nil {
logger.Errorf("Failed to connect to main thread: %v", err)
return
}
defer connection.Close()
id := "shutdown"
force := <-wait
if !force {
// Send a request to be unregistered
data, err := proto.Marshal(&processor_pb2.TpUnregisterRequest{})
if err != nil {
logger.Errorf(
"Failed to unregister: %v", err,
)
}
corrId, err := connection.SendNewMsg(
validator_pb2.Message_TP_UNREGISTER_REQUEST, data,
)
if err != nil {
logger.Errorf(
"Failed to unregister: %v", err,
)
}
// Wait for a response
_, msg, err := connection.RecvMsgWithId(corrId)
if err != nil {
logger.Errorf("Failed to receive TpUnregisterResponse: %v", err)
}
if msg.GetCorrelationId() != corrId {
logger.Errorf(
"Expected message with correlation id %v but got %v",
corrId, msg.GetCorrelationId(),
)
}
if msg.GetMessageType() != validator_pb2.Message_TP_UNREGISTER_RESPONSE {
logger.Errorf(
"Expected TP_UNREGISTER_RESPONSE but got %v", msg.GetMessageType(),
)
}
}
// Close the work queue, telling the worker threads there's no more work
close(queue)
err = connection.SendMsg(
validator_pb2.Message_DEFAULT,
[]byte{byte(0)}, "shutdown",
)
if err != nil {
logger.Errorf("(%v) Error sending shutdown message to router: %v", id, err)
} else {
logger.Infof("(%v) Sent shutdown message to router", id)
}
}