-
Notifications
You must be signed in to change notification settings - Fork 175
/
manager.go
325 lines (264 loc) · 9.02 KB
/
manager.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
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
package computation
import (
"context"
"encoding/hex"
"fmt"
"math/rand"
"strings"
"sync"
"time"
jsoncdc "github.com/onflow/cadence/encoding/json"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"golang.org/x/sync/errgroup"
"github.com/onflow/flow-go/engine/execution"
"github.com/onflow/flow-go/engine/execution/computation/computer"
"github.com/onflow/flow-go/engine/execution/computation/computer/uploader"
"github.com/onflow/flow-go/fvm"
"github.com/onflow/flow-go/fvm/programs"
"github.com/onflow/flow-go/fvm/state"
"github.com/onflow/flow-go/model/flow"
"github.com/onflow/flow-go/module"
"github.com/onflow/flow-go/module/executiondatasync/provider"
"github.com/onflow/flow-go/module/mempool/entity"
"github.com/onflow/flow-go/module/trace"
"github.com/onflow/flow-go/state/protocol"
"github.com/onflow/flow-go/utils/debug"
"github.com/onflow/flow-go/utils/logging"
)
var uploadEnabled = true
func SetUploaderEnabled(enabled bool) {
uploadEnabled = enabled
log.Info().Msgf("changed uploadEnabled to %v", enabled)
}
func GetUploaderEnabled() bool {
return uploadEnabled
}
type VirtualMachine interface {
Run(fvm.Context, fvm.Procedure, state.View, *programs.Programs) error
GetAccount(fvm.Context, flow.Address, state.View, *programs.Programs) (*flow.Account, error)
}
type ComputationManager interface {
ExecuteScript(context.Context, []byte, [][]byte, *flow.Header, state.View) ([]byte, error)
ComputeBlock(
ctx context.Context,
block *entity.ExecutableBlock,
view state.View,
) (*execution.ComputationResult, error)
GetAccount(addr flow.Address, header *flow.Header, view state.View) (*flow.Account, error)
}
var DefaultScriptLogThreshold = 1 * time.Second
var DefaultScriptExecutionTimeLimit = 10 * time.Second
const MaxScriptErrorMessageSize = 1000 // 1000 chars
// Manager manages computation and execution
type Manager struct {
log zerolog.Logger
tracer module.Tracer
metrics module.ExecutionMetrics
me module.Local
protoState protocol.State
vm VirtualMachine
vmCtx fvm.Context
blockComputer computer.BlockComputer
programsCache *ProgramsCache
scriptLogThreshold time.Duration
scriptExecutionTimeLimit time.Duration
uploaders []uploader.Uploader
rngLock *sync.Mutex
rng *rand.Rand
}
func New(
logger zerolog.Logger,
metrics module.ExecutionMetrics,
tracer module.Tracer,
me module.Local,
protoState protocol.State,
vm VirtualMachine,
vmCtx fvm.Context,
programsCacheSize uint,
committer computer.ViewCommitter,
scriptLogThreshold time.Duration,
scriptExecutionTimeLimit time.Duration,
uploaders []uploader.Uploader,
executionDataProvider *provider.Provider,
) (*Manager, error) {
log := logger.With().Str("engine", "computation").Logger()
blockComputer, err := computer.NewBlockComputer(
vm,
vmCtx,
metrics,
tracer,
log.With().Str("component", "block_computer").Logger(),
committer,
executionDataProvider,
)
if err != nil {
return nil, fmt.Errorf("cannot create block computer: %w", err)
}
programsCache, err := NewProgramsCache(programsCacheSize)
if err != nil {
return nil, fmt.Errorf("cannot create programs cache: %w", err)
}
e := Manager{
log: log,
tracer: tracer,
metrics: metrics,
me: me,
protoState: protoState,
vm: vm,
vmCtx: vmCtx,
blockComputer: blockComputer,
programsCache: programsCache,
scriptLogThreshold: scriptLogThreshold,
scriptExecutionTimeLimit: scriptExecutionTimeLimit,
uploaders: uploaders,
rngLock: &sync.Mutex{},
rng: rand.New(rand.NewSource(time.Now().UnixNano())),
}
return &e, nil
}
func (e *Manager) getChildProgramsOrEmpty(blockID flow.Identifier) *programs.Programs {
blockPrograms := e.programsCache.Get(blockID)
if blockPrograms == nil {
return programs.NewEmptyPrograms()
}
return blockPrograms.ChildPrograms()
}
func (e *Manager) ExecuteScript(
ctx context.Context,
code []byte,
arguments [][]byte,
blockHeader *flow.Header,
view state.View,
) ([]byte, 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.log.Debug().Enabled() {
e.rngLock.Lock()
trackerID := e.rng.Uint32()
e.rngLock.Unlock()
trackedLogger := e.log.With().Hex("script_hex", code).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.scriptExecutionTimeLimit)
defer cancel()
script := fvm.NewScriptWithContextAndArgs(code, requestCtx, arguments...)
blockCtx := fvm.NewContextFromParent(e.vmCtx, fvm.WithBlockHeader(blockHeader))
programs := e.getChildProgramsOrEmpty(blockHeader.ID())
err := func() (err error) {
start := time.Now()
defer func() {
prepareLog := func() *zerolog.Event {
args := make([]string, 0, len(arguments))
for _, a := range arguments {
args = append(args, hex.EncodeToString(a))
}
return e.log.Error().
Hex("script_hex", code).
Str("args", strings.Join(args, ","))
}
elapsed := time.Since(start)
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.scriptLogThreshold {
prepareLog().
Dur("duration", elapsed).
Msg("script execution exceeded threshold")
}
}()
return e.vm.Run(blockCtx, script, view, programs)
}()
if err != nil {
return nil, fmt.Errorf("failed to execute script (internal error): %w", err)
}
if script.Err != nil {
scriptErrMsg := script.Err.Error()
if len(scriptErrMsg) > MaxScriptErrorMessageSize {
split := int(MaxScriptErrorMessageSize/2) - 1
var sb strings.Builder
sb.WriteString(scriptErrMsg[:split])
sb.WriteString(" ... ")
sb.WriteString(scriptErrMsg[len(scriptErrMsg)-split:])
scriptErrMsg = sb.String()
}
return nil, fmt.Errorf("failed to execute script at block (%s): %s", blockHeader.ID(), scriptErrMsg)
}
encodedValue, err := jsoncdc.Encode(script.Value)
if err != nil {
return nil, fmt.Errorf("failed to encode runtime value: %w", err)
}
memAllocAfter := debug.GetHeapAllocsBytes()
e.metrics.ExecutionScriptExecuted(time.Since(startedAt), script.GasUsed, memAllocAfter-memAllocBefore, script.MemoryEstimate)
return encodedValue, nil
}
func (e *Manager) ComputeBlock(
ctx context.Context,
block *entity.ExecutableBlock,
view state.View,
) (*execution.ComputationResult, error) {
e.log.Debug().
Hex("block_id", logging.Entity(block.Block)).
Msg("received complete block")
var blockPrograms *programs.Programs
fromCache := e.programsCache.Get(block.ParentID())
if fromCache == nil {
blockPrograms = programs.NewEmptyPrograms()
} else {
blockPrograms = fromCache.ChildPrograms()
}
result, err := e.blockComputer.ExecuteBlock(ctx, block, view, blockPrograms)
if err != nil {
e.log.Error().
Hex("block_id", logging.Entity(block.Block)).
Msg("failed to compute block result")
return nil, fmt.Errorf("failed to execute block: %w", err)
}
e.log.Debug().Hex("block_id", logging.Entity(block.Block)).Msg("block result computed")
toInsert := blockPrograms
// if we have item from cache and there were no changes
// insert it under new block, to prevent long chains
if fromCache != nil && !blockPrograms.HasChanges() {
toInsert = fromCache
}
e.programsCache.Set(block.ID(), toInsert)
e.log.Debug().Hex("block_id", logging.Entity(block.Block)).Msg("programs cache updated")
if uploadEnabled {
var group errgroup.Group
for _, uploader := range e.uploaders {
uploader := uploader
group.Go(func() error {
span, _ := e.tracer.StartSpanFromContext(ctx, trace.EXEUploadCollections)
defer span.End()
return uploader.Upload(result)
})
}
err = group.Wait()
if err != nil {
return nil, fmt.Errorf("failed to upload block result: %w", err)
}
}
e.log.Debug().
Hex("block_id", logging.Entity(result.ExecutableBlock.Block)).
Msg("computed block result")
return result, nil
}
func (e *Manager) GetAccount(address flow.Address, blockHeader *flow.Header, view state.View) (*flow.Account, error) {
blockCtx := fvm.NewContextFromParent(e.vmCtx, fvm.WithBlockHeader(blockHeader))
programs := e.getChildProgramsOrEmpty(blockHeader.ID())
account, err := e.vm.GetAccount(blockCtx, address, view, programs)
if err != nil {
return nil, fmt.Errorf("failed to get account (%s) at block (%s): %w", address.String(), blockHeader.ID(), err)
}
return account, nil
}