-
Notifications
You must be signed in to change notification settings - Fork 208
Expand file tree
/
Copy pathexecutor.go
More file actions
248 lines (218 loc) · 5.97 KB
/
executor.go
File metadata and controls
248 lines (218 loc) · 5.97 KB
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
package query
import (
"context"
"encoding/hex"
"fmt"
"strings"
"sync"
"time"
"github.com/onflow/flow-go/fvm/errors"
jsoncdc "github.com/onflow/cadence/encoding/json"
"github.com/rs/zerolog"
"github.com/onflow/flow-go/fvm"
"github.com/onflow/flow-go/fvm/storage/derived"
"github.com/onflow/flow-go/fvm/storage/snapshot"
"github.com/onflow/flow-go/model/flow"
"github.com/onflow/flow-go/module"
"github.com/onflow/flow-go/utils/debug"
"github.com/onflow/flow-go/utils/rand"
)
const (
DefaultLogTimeThreshold = 1 * time.Second
DefaultExecutionTimeLimit = 10 * time.Second
DefaultMaxErrorMessageSize = 1000 // 1000 chars
)
type Executor interface {
ExecuteScript(
ctx context.Context,
script []byte,
arguments [][]byte,
blockHeader *flow.Header,
snapshot snapshot.StorageSnapshot,
) (
[]byte,
error,
)
GetAccount(
ctx context.Context,
addr flow.Address,
header *flow.Header,
snapshot snapshot.StorageSnapshot,
) (
*flow.Account,
error,
)
}
type QueryConfig struct {
LogTimeThreshold time.Duration
ExecutionTimeLimit time.Duration
ComputationLimit uint64
MaxErrorMessageSize int
}
func NewDefaultConfig() QueryConfig {
return QueryConfig{
LogTimeThreshold: DefaultLogTimeThreshold,
ExecutionTimeLimit: DefaultExecutionTimeLimit,
ComputationLimit: fvm.DefaultComputationLimit,
MaxErrorMessageSize: DefaultMaxErrorMessageSize,
}
}
type QueryExecutor struct {
config QueryConfig
logger zerolog.Logger
metrics module.ExecutionMetrics
vm fvm.VM
vmCtx fvm.Context
derivedChainData *derived.DerivedChainData
rngLock *sync.Mutex
entropyPerBlock EntropyProviderPerBlock
}
var _ Executor = &QueryExecutor{}
func NewQueryExecutor(
config QueryConfig,
logger zerolog.Logger,
metrics module.ExecutionMetrics,
vm fvm.VM,
vmCtx fvm.Context,
derivedChainData *derived.DerivedChainData,
entropyPerBlock EntropyProviderPerBlock,
) *QueryExecutor {
if config.ComputationLimit > 0 {
vmCtx = fvm.NewContextFromParent(vmCtx, fvm.WithComputationLimit(config.ComputationLimit))
}
return &QueryExecutor{
config: config,
logger: logger,
metrics: metrics,
vm: vm,
vmCtx: vmCtx,
derivedChainData: derivedChainData,
rngLock: &sync.Mutex{},
entropyPerBlock: entropyPerBlock,
}
}
func (e *QueryExecutor) ExecuteScript(
ctx context.Context,
script []byte,
arguments [][]byte,
blockHeader *flow.Header,
snapshot snapshot.StorageSnapshot,
) (
encodedValue []byte,
err error,
) {
startedAt := time.Now()
memAllocBefore := debug.GetHeapAllocsBytes()
// allocate a random ID to be able to track this script when its done,
// scripts might not be unique so we use this extra tracker to follow their logs
// TODO: this is a temporary measure, we could remove this in the future
if e.logger.Debug().Enabled() {
e.rngLock.Lock()
defer e.rngLock.Unlock()
trackerID, err := rand.Uint32()
if err != nil {
return nil, fmt.Errorf("failed to generate trackerID: %w", err)
}
trackedLogger := e.logger.With().Hex("script_hex", script).Uint32("trackerID", trackerID).Logger()
trackedLogger.Debug().Msg("script is sent for execution")
defer func() {
trackedLogger.Debug().Msg("script execution is complete")
}()
}
requestCtx, cancel := context.WithTimeout(ctx, e.config.ExecutionTimeLimit)
defer cancel()
defer func() {
prepareLog := func() *zerolog.Event {
args := make([]string, 0, len(arguments))
for _, a := range arguments {
args = append(args, hex.EncodeToString(a))
}
return e.logger.Error().
Hex("script_hex", script).
Str("args", strings.Join(args, ","))
}
elapsed := time.Since(startedAt)
if r := recover(); r != nil {
prepareLog().
Interface("recovered", r).
Msg("script execution caused runtime panic")
err = fmt.Errorf("cadence runtime error: %s", r)
return
}
if elapsed >= e.config.LogTimeThreshold {
prepareLog().
Dur("duration", elapsed).
Msg("script execution exceeded threshold")
}
}()
var output fvm.ProcedureOutput
_, output, err = e.vm.Run(
fvm.NewContextFromParent(
e.vmCtx,
fvm.WithBlockHeader(blockHeader),
fvm.WithEntropyProvider(e.entropyPerBlock.AtBlockID(blockHeader.ID())),
fvm.WithDerivedBlockData(
e.derivedChainData.NewDerivedBlockDataForScript(blockHeader.ID()))),
fvm.NewScriptWithContextAndArgs(script, requestCtx, arguments...),
snapshot)
if err != nil {
return nil, fmt.Errorf("failed to execute script (internal error): %w", err)
}
if output.Err != nil {
return nil, errors.NewCodedError(
output.Err.Code(),
"failed to execute script at block (%s): %s", blockHeader.ID(),
summarizeLog(output.Err.Error(), e.config.MaxErrorMessageSize),
)
}
encodedValue, err = jsoncdc.Encode(output.Value)
if err != nil {
return nil, fmt.Errorf("failed to encode runtime value: %w", err)
}
memAllocAfter := debug.GetHeapAllocsBytes()
e.metrics.ExecutionScriptExecuted(
time.Since(startedAt),
output.ComputationUsed,
memAllocAfter-memAllocBefore,
output.MemoryEstimate)
return encodedValue, nil
}
func summarizeLog(log string, limit int) string {
if limit > 0 && len(log) > limit {
split := int(limit/2) - 1
var sb strings.Builder
sb.WriteString(log[:split])
sb.WriteString(" ... ")
sb.WriteString(log[len(log)-split:])
return sb.String()
}
return log
}
func (e *QueryExecutor) GetAccount(
ctx context.Context,
address flow.Address,
blockHeader *flow.Header,
snapshot snapshot.StorageSnapshot,
) (
*flow.Account,
error,
) {
// TODO(ramtin): utilize ctx
blockCtx := fvm.NewContextFromParent(
e.vmCtx,
fvm.WithBlockHeader(blockHeader),
fvm.WithDerivedBlockData(
e.derivedChainData.NewDerivedBlockDataForScript(blockHeader.ID())))
account, err := e.vm.GetAccount(
blockCtx,
address,
snapshot)
if err != nil {
return nil, fmt.Errorf(
"failed to get account (%s) at block (%s): %w",
address.String(),
blockHeader.ID(),
err)
}
return account, nil
}