-
Notifications
You must be signed in to change notification settings - Fork 131
/
service.go
506 lines (428 loc) · 15.2 KB
/
service.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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
package handlers
import (
"context"
"errors"
"fmt"
"io/ioutil"
"log"
"github.com/creachadair/jrpc2"
"github.com/creachadair/jrpc2/code"
rpch "github.com/creachadair/jrpc2/handler"
"github.com/hashicorp/hcl-lang/decoder"
"github.com/hashicorp/hcl-lang/schema"
lsctx "github.com/hashicorp/terraform-ls/internal/context"
idecoder "github.com/hashicorp/terraform-ls/internal/decoder"
"github.com/hashicorp/terraform-ls/internal/filesystem"
"github.com/hashicorp/terraform-ls/internal/langserver/diagnostics"
"github.com/hashicorp/terraform-ls/internal/langserver/session"
ilsp "github.com/hashicorp/terraform-ls/internal/lsp"
lsp "github.com/hashicorp/terraform-ls/internal/protocol"
"github.com/hashicorp/terraform-ls/internal/schemas"
"github.com/hashicorp/terraform-ls/internal/settings"
"github.com/hashicorp/terraform-ls/internal/state"
"github.com/hashicorp/terraform-ls/internal/terraform/discovery"
"github.com/hashicorp/terraform-ls/internal/terraform/exec"
"github.com/hashicorp/terraform-ls/internal/terraform/module"
)
type service struct {
logger *log.Logger
srvCtx context.Context
sessCtx context.Context
stopSession context.CancelFunc
fs filesystem.Filesystem
modStore *state.ModuleStore
schemaStore *state.ProviderSchemaStore
watcher module.Watcher
walker *module.Walker
modMgr module.ModuleManager
newModuleManager module.ModuleManagerFactory
newWatcher module.WatcherFactory
newWalker module.WalkerFactory
tfDiscoFunc discovery.DiscoveryFunc
tfExecFactory exec.ExecutorFactory
tfExecOpts *exec.ExecutorOpts
additionalHandlers map[string]rpch.Func
}
var discardLogs = log.New(ioutil.Discard, "", 0)
func NewSession(srvCtx context.Context) session.Session {
fs := filesystem.NewFilesystem()
d := &discovery.Discovery{}
sessCtx, stopSession := context.WithCancel(srvCtx)
return &service{
logger: discardLogs,
fs: fs,
srvCtx: srvCtx,
sessCtx: sessCtx,
stopSession: stopSession,
newModuleManager: module.NewModuleManager,
newWatcher: module.NewWatcher,
newWalker: module.NewWalker,
tfDiscoFunc: d.LookPath,
tfExecFactory: exec.NewExecutor,
}
}
func (svc *service) SetLogger(logger *log.Logger) {
svc.logger = logger
}
// Assigner builds out the jrpc2.Map according to the LSP protocol
// and passes related dependencies to handlers via context
func (svc *service) Assigner() (jrpc2.Assigner, error) {
svc.logger.Println("Preparing new session ...")
session := session.NewSession(svc.stopSession)
err := session.Prepare()
if err != nil {
return nil, fmt.Errorf("Unable to prepare session: %w", err)
}
svc.fs.SetLogger(svc.logger)
lh := LogHandler(svc.logger)
cc := &lsp.ClientCapabilities{}
notifier := diagnostics.NewNotifier(svc.sessCtx, svc.logger)
rootDir := ""
commandPrefix := ""
clientName := ""
var expFeatures settings.ExperimentalFeatures
m := map[string]rpch.Func{
"initialize": func(ctx context.Context, req *jrpc2.Request) (interface{}, error) {
err := session.Initialize(req)
if err != nil {
return nil, err
}
ctx = lsctx.WithClientCapabilitiesSetter(ctx, cc)
ctx = lsctx.WithRootDirectory(ctx, &rootDir)
ctx = lsctx.WithCommandPrefix(ctx, &commandPrefix)
ctx = lsctx.WithClientName(ctx, &clientName)
ctx = lsctx.WithExperimentalFeatures(ctx, &expFeatures)
version, ok := lsctx.LanguageServerVersion(svc.srvCtx)
if ok {
ctx = lsctx.WithLanguageServerVersion(ctx, version)
}
return handle(ctx, req, svc.Initialize)
},
"initialized": func(ctx context.Context, req *jrpc2.Request) (interface{}, error) {
err := session.ConfirmInitialization(req)
if err != nil {
return nil, err
}
return handle(ctx, req, Initialized)
},
"textDocument/didChange": func(ctx context.Context, req *jrpc2.Request) (interface{}, error) {
err := session.CheckInitializationIsConfirmed()
if err != nil {
return nil, err
}
ctx = lsctx.WithDiagnosticsNotifier(ctx, notifier)
ctx = lsctx.WithDocumentStorage(ctx, svc.fs)
ctx = lsctx.WithModuleManager(ctx, svc.modMgr)
return handle(ctx, req, TextDocumentDidChange)
},
"textDocument/didOpen": func(ctx context.Context, req *jrpc2.Request) (interface{}, error) {
err := session.CheckInitializationIsConfirmed()
if err != nil {
return nil, err
}
ctx = lsctx.WithDiagnosticsNotifier(ctx, notifier)
ctx = lsctx.WithDocumentStorage(ctx, svc.fs)
ctx = lsctx.WithModuleManager(ctx, svc.modMgr)
ctx = lsctx.WithWatcher(ctx, svc.watcher)
return handle(ctx, req, lh.TextDocumentDidOpen)
},
"textDocument/didClose": func(ctx context.Context, req *jrpc2.Request) (interface{}, error) {
err := session.CheckInitializationIsConfirmed()
if err != nil {
return nil, err
}
ctx = lsctx.WithDocumentStorage(ctx, svc.fs)
return handle(ctx, req, TextDocumentDidClose)
},
"textDocument/documentSymbol": func(ctx context.Context, req *jrpc2.Request) (interface{}, error) {
err := session.CheckInitializationIsConfirmed()
if err != nil {
return nil, err
}
ctx = lsctx.WithDocumentStorage(ctx, svc.fs)
ctx = lsctx.WithClientCapabilities(ctx, cc)
ctx = lsctx.WithModuleFinder(ctx, svc.modMgr)
return handle(ctx, req, lh.TextDocumentSymbol)
},
"textDocument/documentLink": func(ctx context.Context, req *jrpc2.Request) (interface{}, error) {
err := session.CheckInitializationIsConfirmed()
if err != nil {
return nil, err
}
ctx = lsctx.WithDocumentStorage(ctx, svc.fs)
ctx = lsctx.WithClientCapabilities(ctx, cc)
ctx = lsctx.WithClientName(ctx, &clientName)
ctx = lsctx.WithModuleFinder(ctx, svc.modMgr)
return handle(ctx, req, lh.TextDocumentLink)
},
"textDocument/declaration": func(ctx context.Context, req *jrpc2.Request) (interface{}, error) {
err := session.CheckInitializationIsConfirmed()
if err != nil {
return nil, err
}
ctx = lsctx.WithDocumentStorage(ctx, svc.fs)
ctx = lsctx.WithClientCapabilities(ctx, cc)
ctx = lsctx.WithModuleFinder(ctx, svc.modMgr)
return handle(ctx, req, lh.GoToReferenceTarget)
},
"textDocument/definition": func(ctx context.Context, req *jrpc2.Request) (interface{}, error) {
err := session.CheckInitializationIsConfirmed()
if err != nil {
return nil, err
}
ctx = lsctx.WithDocumentStorage(ctx, svc.fs)
ctx = lsctx.WithClientCapabilities(ctx, cc)
ctx = lsctx.WithModuleFinder(ctx, svc.modMgr)
return handle(ctx, req, lh.GoToReferenceTarget)
},
"textDocument/completion": func(ctx context.Context, req *jrpc2.Request) (interface{}, error) {
err := session.CheckInitializationIsConfirmed()
if err != nil {
return nil, err
}
ctx = lsctx.WithDocumentStorage(ctx, svc.fs)
ctx = lsctx.WithClientCapabilities(ctx, cc)
ctx = lsctx.WithModuleFinder(ctx, svc.modMgr)
return handle(ctx, req, lh.TextDocumentComplete)
},
"textDocument/hover": func(ctx context.Context, req *jrpc2.Request) (interface{}, error) {
err := session.CheckInitializationIsConfirmed()
if err != nil {
return nil, err
}
ctx = lsctx.WithDocumentStorage(ctx, svc.fs)
ctx = lsctx.WithClientCapabilities(ctx, cc)
ctx = lsctx.WithClientName(ctx, &clientName)
ctx = lsctx.WithModuleFinder(ctx, svc.modMgr)
return handle(ctx, req, lh.TextDocumentHover)
},
"textDocument/codeLens": func(ctx context.Context, req *jrpc2.Request) (interface{}, error) {
err := session.CheckInitializationIsConfirmed()
if err != nil {
return nil, err
}
ctx = lsctx.WithClientCapabilities(ctx, cc)
ctx = lsctx.WithDocumentStorage(ctx, svc.fs)
ctx = lsctx.WithModuleFinder(ctx, svc.modMgr)
return handle(ctx, req, lh.TextDocumentCodeLens)
},
"textDocument/formatting": func(ctx context.Context, req *jrpc2.Request) (interface{}, error) {
err := session.CheckInitializationIsConfirmed()
if err != nil {
return nil, err
}
ctx = lsctx.WithDocumentStorage(ctx, svc.fs)
ctx = exec.WithExecutorOpts(ctx, svc.tfExecOpts)
ctx = exec.WithExecutorFactory(ctx, svc.tfExecFactory)
return handle(ctx, req, lh.TextDocumentFormatting)
},
"textDocument/semanticTokens/full": func(ctx context.Context, req *jrpc2.Request) (interface{}, error) {
err := session.CheckInitializationIsConfirmed()
if err != nil {
return nil, err
}
ctx = lsctx.WithDocumentStorage(ctx, svc.fs)
ctx = lsctx.WithClientCapabilities(ctx, cc)
ctx = lsctx.WithModuleFinder(ctx, svc.modMgr)
return handle(ctx, req, lh.TextDocumentSemanticTokensFull)
},
"textDocument/didSave": func(ctx context.Context, req *jrpc2.Request) (interface{}, error) {
err := session.CheckInitializationIsConfirmed()
if err != nil {
return nil, err
}
ctx = lsctx.WithDiagnosticsNotifier(ctx, notifier)
ctx = lsctx.WithExperimentalFeatures(ctx, &expFeatures)
ctx = lsctx.WithModuleFinder(ctx, svc.modMgr)
ctx = exec.WithExecutorOpts(ctx, svc.tfExecOpts)
return handle(ctx, req, lh.TextDocumentDidSave)
},
"workspace/didChangeWorkspaceFolders": func(ctx context.Context, req *jrpc2.Request) (interface{}, error) {
err := session.CheckInitializationIsConfirmed()
if err != nil {
return nil, err
}
ctx = lsctx.WithModuleWalker(ctx, svc.walker)
ctx = lsctx.WithWatcher(ctx, svc.watcher)
return handle(ctx, req, lh.DidChangeWorkspaceFolders)
},
"textDocument/references": func(ctx context.Context, req *jrpc2.Request) (interface{}, error) {
err := session.CheckInitializationIsConfirmed()
if err != nil {
return nil, err
}
ctx = lsctx.WithDocumentStorage(ctx, svc.fs)
ctx = lsctx.WithModuleFinder(ctx, svc.modMgr)
return handle(ctx, req, lh.References)
},
"workspace/executeCommand": func(ctx context.Context, req *jrpc2.Request) (interface{}, error) {
err := session.CheckInitializationIsConfirmed()
if err != nil {
return nil, err
}
ctx = lsctx.WithCommandPrefix(ctx, &commandPrefix)
ctx = lsctx.WithModuleManager(ctx, svc.modMgr)
ctx = lsctx.WithModuleFinder(ctx, svc.modMgr)
ctx = lsctx.WithModuleWalker(ctx, svc.walker)
ctx = lsctx.WithWatcher(ctx, svc.watcher)
ctx = lsctx.WithRootDirectory(ctx, &rootDir)
ctx = lsctx.WithDiagnosticsNotifier(ctx, notifier)
ctx = exec.WithExecutorOpts(ctx, svc.tfExecOpts)
ctx = exec.WithExecutorFactory(ctx, svc.tfExecFactory)
return handle(ctx, req, lh.WorkspaceExecuteCommand)
},
"workspace/symbol": func(ctx context.Context, req *jrpc2.Request) (interface{}, error) {
err := session.CheckInitializationIsConfirmed()
if err != nil {
return nil, err
}
ctx = lsctx.WithDocumentStorage(ctx, svc.fs)
ctx = lsctx.WithClientCapabilities(ctx, cc)
ctx = lsctx.WithModuleFinder(ctx, svc.modMgr)
return handle(ctx, req, lh.WorkspaceSymbol)
},
"shutdown": func(ctx context.Context, req *jrpc2.Request) (interface{}, error) {
err := session.Shutdown(req)
if err != nil {
return nil, err
}
ctx = lsctx.WithDocumentStorage(ctx, svc.fs)
svc.shutdown()
return handle(ctx, req, Shutdown)
},
"exit": func(ctx context.Context, req *jrpc2.Request) (interface{}, error) {
err := session.Exit()
if err != nil {
return nil, err
}
svc.stopSession()
return nil, nil
},
"$/cancelRequest": func(ctx context.Context, req *jrpc2.Request) (interface{}, error) {
err := session.CheckInitializationIsConfirmed()
if err != nil {
return nil, err
}
return handle(ctx, req, CancelRequest)
},
}
// For use in tests, e.g. to test request cancellation
if len(svc.additionalHandlers) > 0 {
for methodName, handlerFunc := range svc.additionalHandlers {
m[methodName] = handlerFunc
}
}
return convertMap(m), nil
}
func (svc *service) configureSessionDependencies(cfgOpts *settings.Options) error {
// The following is set via CLI flags, hence available in the server context
execOpts := &exec.ExecutorOpts{}
cliExecPath, ok := lsctx.TerraformExecPath(svc.srvCtx)
if ok {
if len(cfgOpts.TerraformExecPath) > 0 {
return fmt.Errorf("Terraform exec path can either be set via (-tf-exec) CLI flag " +
"or (terraformExecPath) LSP config option, not both")
}
execOpts.ExecPath = cliExecPath
} else if len(cfgOpts.TerraformExecPath) > 0 {
execOpts.ExecPath = cfgOpts.TerraformExecPath
} else {
path, err := svc.tfDiscoFunc()
if err == nil {
execOpts.ExecPath = path
}
}
svc.srvCtx = lsctx.WithTerraformExecPath(svc.srvCtx, execOpts.ExecPath)
if path, ok := lsctx.TerraformExecLogPath(svc.srvCtx); ok {
execOpts.ExecLogPath = path
}
if timeout, ok := lsctx.TerraformExecTimeout(svc.srvCtx); ok {
execOpts.Timeout = timeout
}
svc.tfExecOpts = execOpts
svc.sessCtx = exec.WithExecutorOpts(svc.sessCtx, execOpts)
svc.sessCtx = exec.WithExecutorFactory(svc.sessCtx, svc.tfExecFactory)
store, err := state.NewStateStore()
if err != nil {
return err
}
store.SetLogger(svc.logger)
err = schemas.PreloadSchemasToStore(store.ProviderSchemas)
if err != nil {
return err
}
svc.modMgr = svc.newModuleManager(svc.sessCtx, svc.fs, store.Modules, store.ProviderSchemas)
svc.modMgr.SetLogger(svc.logger)
svc.walker = svc.newWalker(svc.fs, svc.modMgr)
svc.walker.SetLogger(svc.logger)
ww, err := svc.newWatcher(svc.fs, svc.modMgr)
if err != nil {
return err
}
svc.watcher = ww
svc.watcher.SetLogger(svc.logger)
err = svc.watcher.Start()
if err != nil {
return err
}
return nil
}
func (svc *service) Finish(_ jrpc2.Assigner, status jrpc2.ServerStatus) {
if status.Closed || status.Err != nil {
svc.logger.Printf("session stopped unexpectedly (err: %v)", status.Err)
}
svc.shutdown()
svc.stopSession()
}
func (svc *service) shutdown() {
if svc.walker != nil {
svc.logger.Printf("stopping walker for session ...")
svc.walker.Stop()
svc.logger.Printf("walker stopped")
}
if svc.watcher != nil {
svc.logger.Println("stopping watcher for session ...")
err := svc.watcher.Stop()
if err != nil {
svc.logger.Println("unable to stop watcher for session:", err)
} else {
svc.logger.Println("watcher stopped")
}
}
if svc.modMgr != nil {
svc.logger.Println("cancelling any module loading ...")
svc.modMgr.CancelLoading()
svc.logger.Println("module loading cancelled")
}
}
// convertMap is a helper function allowing us to omit the jrpc2.Func
// signature from the method definitions
func convertMap(m map[string]rpch.Func) rpch.Map {
hm := make(rpch.Map, len(m))
for method, fun := range m {
hm[method] = rpch.New(fun)
}
return hm
}
const requestCancelled code.Code = -32800
// handle calls a jrpc2.Func compatible function
func handle(ctx context.Context, req *jrpc2.Request, fn interface{}) (interface{}, error) {
f := rpch.New(fn)
result, err := f.Handle(ctx, req)
if ctx.Err() != nil && errors.Is(ctx.Err(), context.Canceled) {
err = fmt.Errorf("%w: %s", requestCancelled.Err(), err)
}
return result, err
}
func schemaForDocument(mf module.ModuleFinder, doc filesystem.Document) (*schema.BodySchema, error) {
if doc.LanguageID() == ilsp.Tfvars.String() {
return mf.SchemaForVariables(doc.Dir())
}
return mf.SchemaForModule(doc.Dir())
}
func decoderForDocument(ctx context.Context, mod module.Module, languageID string) (*decoder.Decoder, error) {
if languageID == ilsp.Tfvars.String() {
return idecoder.DecoderForVariables(mod)
}
return idecoder.DecoderForModule(ctx, mod)
}