-
-
Notifications
You must be signed in to change notification settings - Fork 398
/
Copy pathinstances.go
357 lines (310 loc) · 10.7 KB
/
instances.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
// This file is part of arduino-cli.
//
// Copyright 2020 ARDUINO SA (http://www.arduino.cc/)
//
// This software is released under the GNU General Public License version 3,
// which covers the main part of arduino-cli.
// The terms of this license can be found at:
// https://www.gnu.org/licenses/gpl-3.0.en.html
//
// You can be released from the requirements of the above licenses by purchasing
// a commercial license. Buying such a license is mandatory if you want to
// modify or otherwise use the software for commercial activities involving the
// Arduino software without disclosing the source code of your own applications.
// To purchase a commercial license, send an email to [email protected].
package commands
import (
"context"
"fmt"
"io/ioutil"
"net/url"
"path"
"github.com/arduino/arduino-cli/arduino/cores"
"github.com/arduino/arduino-cli/arduino/cores/packageindex"
"github.com/arduino/arduino-cli/arduino/cores/packagemanager"
"github.com/arduino/arduino-cli/arduino/libraries"
"github.com/arduino/arduino-cli/arduino/libraries/librariesmanager"
"github.com/arduino/arduino-cli/cli/globals"
"github.com/arduino/arduino-cli/configuration"
rpc "github.com/arduino/arduino-cli/rpc/commands"
paths "github.com/arduino/go-paths-helper"
"github.com/sirupsen/logrus"
"github.com/spf13/viper"
"go.bug.st/downloader/v2"
)
// this map contains all the running Arduino Core Services instances
// referenced by an int32 handle
var instances = map[int32]*CoreInstance{}
var instancesCount int32 = 1
// CoreInstance is an instance of the Arduino Core Services. The user can
// instantiate as many as needed by providing a different configuration
// for each one.
type CoreInstance struct {
PackageManager *packagemanager.PackageManager
lm *librariesmanager.LibrariesManager
getLibOnly bool
}
// InstanceContainer FIXMEDOC
type InstanceContainer interface {
GetInstance() *rpc.Instance
}
type createInstanceResult struct {
Pm *packagemanager.PackageManager
Lm *librariesmanager.LibrariesManager
PlatformIndexErrors []string
LibrariesIndexError string
}
// GetInstance returns a CoreInstance for the given ID, or nil if ID
// doesn't exist
func GetInstance(id int32) *CoreInstance {
return instances[id]
}
// GetPackageManager returns a PackageManager for the given ID, or nil if
// ID doesn't exist
func GetPackageManager(id int32) *packagemanager.PackageManager {
i, ok := instances[id]
if !ok {
return nil
}
return i.PackageManager
}
// GetLibraryManager returns the library manager for the given instance ID
func GetLibraryManager(instanceID int32) *librariesmanager.LibrariesManager {
i, ok := instances[instanceID]
if !ok {
return nil
}
return i.lm
}
func (instance *CoreInstance) installToolIfMissing(tool *cores.ToolRelease, downloadCB DownloadProgressCB, taskCB TaskProgressCB) (bool, error) {
if tool.IsInstalled() {
return false, nil
}
taskCB(&rpc.TaskProgress{Name: "Downloading missing tool " + tool.String()})
if err := DownloadToolRelease(instance.PackageManager, tool, downloadCB); err != nil {
return false, fmt.Errorf("downloading %s tool: %s", tool, err)
}
taskCB(&rpc.TaskProgress{Completed: true})
if err := InstallToolRelease(instance.PackageManager, tool, taskCB); err != nil {
return false, fmt.Errorf("installing %s tool: %s", tool, err)
}
return true, nil
}
func (instance *CoreInstance) checkForBuiltinTools(downloadCB DownloadProgressCB, taskCB TaskProgressCB) error {
// Check for ctags tool
ctags, _ := getBuiltinCtagsTool(instance.PackageManager)
ctagsInstalled, err := instance.installToolIfMissing(ctags, downloadCB, taskCB)
if err != nil {
return err
}
// Check for bultin serial-discovery tool
serialDiscoveryTool, _ := getBuiltinSerialDiscoveryTool(instance.PackageManager)
serialDiscoveryInstalled, err := instance.installToolIfMissing(serialDiscoveryTool, downloadCB, taskCB)
if err != nil {
return err
}
if ctagsInstalled || serialDiscoveryInstalled {
if err := instance.PackageManager.LoadHardware(); err != nil {
return fmt.Errorf("could not load hardware packages: %s", err)
}
}
return nil
}
// Init FIXMEDOC
func Init(ctx context.Context, req *rpc.InitReq, downloadCB DownloadProgressCB, taskCB TaskProgressCB) (*rpc.InitResp, error) {
res, err := createInstance(ctx, req.GetLibraryManagerOnly())
if err != nil {
return nil, fmt.Errorf("cannot initialize package manager: %s", err)
}
instance := &CoreInstance{
PackageManager: res.Pm,
lm: res.Lm,
getLibOnly: req.GetLibraryManagerOnly(),
}
handle := instancesCount
instancesCount++
instances[handle] = instance
if err := instance.checkForBuiltinTools(downloadCB, taskCB); err != nil {
return nil, err
}
return &rpc.InitResp{
Instance: &rpc.Instance{Id: handle},
PlatformsIndexErrors: res.PlatformIndexErrors,
LibrariesIndexError: res.LibrariesIndexError,
}, nil
}
// Destroy FIXMEDOC
func Destroy(ctx context.Context, req *rpc.DestroyReq) (*rpc.DestroyResp, error) {
id := req.GetInstance().GetId()
if _, ok := instances[id]; !ok {
return nil, fmt.Errorf("invalid handle")
}
delete(instances, id)
return &rpc.DestroyResp{}, nil
}
// UpdateLibrariesIndex updates the library_index.json
func UpdateLibrariesIndex(ctx context.Context, req *rpc.UpdateLibrariesIndexReq, downloadCB func(*rpc.DownloadProgress)) error {
logrus.Info("Updating libraries index")
lm := GetLibraryManager(req.GetInstance().GetId())
if lm == nil {
return fmt.Errorf("invalid handle")
}
config, err := GetDownloaderConfig()
if err != nil {
return err
}
d, err := lm.UpdateIndex(config)
if err != nil {
return err
}
Download(d, "Updating index: library_index.json", downloadCB)
if d.Error() != nil {
return d.Error()
}
if _, err := Rescan(req.GetInstance().GetId()); err != nil {
return fmt.Errorf("rescanning filesystem: %s", err)
}
return nil
}
// UpdateIndex FIXMEDOC
func UpdateIndex(ctx context.Context, req *rpc.UpdateIndexReq, downloadCB DownloadProgressCB) (*rpc.UpdateIndexResp, error) {
id := req.GetInstance().GetId()
_, ok := instances[id]
if !ok {
return nil, fmt.Errorf("invalid handle")
}
indexpath := paths.New(viper.GetString("directories.Data"))
urls := []string{globals.DefaultIndexURL}
urls = append(urls, viper.GetStringSlice("board_manager.additional_urls")...)
for _, u := range urls {
URL, err := url.Parse(u)
if err != nil {
logrus.Warnf("unable to parse additional URL: %s", u)
continue
}
logrus.WithField("url", URL).Print("Updating index")
tmpFile, err := ioutil.TempFile("", "")
if err != nil {
return nil, fmt.Errorf("creating temp file for download: %s", err)
}
if err := tmpFile.Close(); err != nil {
return nil, fmt.Errorf("creating temp file for download: %s", err)
}
tmp := paths.New(tmpFile.Name())
defer tmp.Remove()
config, err := GetDownloaderConfig()
if err != nil {
return nil, fmt.Errorf("downloading index %s: %s", URL, err)
}
d, err := downloader.DownloadWithConfig(tmp.String(), URL.String(), *config)
if err != nil {
return nil, fmt.Errorf("downloading index %s: %s", URL, err)
}
coreIndexPath := indexpath.Join(path.Base(URL.Path))
Download(d, "Updating index: "+coreIndexPath.Base(), downloadCB)
if d.Error() != nil {
return nil, fmt.Errorf("downloading index %s: %s", URL, d.Error())
}
if _, err := packageindex.LoadIndex(tmp); err != nil {
return nil, fmt.Errorf("invalid package index in %s: %s", URL, err)
}
if err := indexpath.MkdirAll(); err != nil {
return nil, fmt.Errorf("can't create data directory %s: %s", indexpath, err)
}
if err := tmp.CopyTo(coreIndexPath); err != nil {
return nil, fmt.Errorf("saving downloaded index %s: %s", URL, err)
}
}
if _, err := Rescan(id); err != nil {
return nil, fmt.Errorf("rescanning filesystem: %s", err)
}
return &rpc.UpdateIndexResp{}, nil
}
// Rescan restart discoveries for the given instance
func Rescan(instanceID int32) (*rpc.RescanResp, error) {
coreInstance, ok := instances[instanceID]
if !ok {
return nil, fmt.Errorf("invalid handle")
}
res, err := createInstance(context.Background(), coreInstance.getLibOnly)
if err != nil {
return nil, fmt.Errorf("rescanning filesystem: %s", err)
}
coreInstance.PackageManager = res.Pm
coreInstance.lm = res.Lm
return &rpc.RescanResp{
PlatformsIndexErrors: res.PlatformIndexErrors,
LibrariesIndexError: res.LibrariesIndexError,
}, nil
}
func createInstance(ctx context.Context, getLibOnly bool) (*createInstanceResult, error) {
res := &createInstanceResult{}
// setup downloads directory
downloadsDir := paths.New(viper.GetString("directories.Downloads"))
if downloadsDir.NotExist() {
err := downloadsDir.MkdirAll()
if err != nil {
return nil, err
}
}
// setup data directory
dataDir := paths.New(viper.GetString("directories.Data"))
packagesDir := configuration.PackagesDir()
if packagesDir.NotExist() {
err := packagesDir.MkdirAll()
if err != nil {
return nil, err
}
}
if !getLibOnly {
res.Pm = packagemanager.NewPackageManager(dataDir, configuration.PackagesDir(),
downloadsDir, dataDir.Join("tmp"))
urls := []string{globals.DefaultIndexURL}
urls = append(urls, viper.GetStringSlice("board_manager.additional_urls")...)
for _, u := range urls {
URL, err := url.Parse(u)
if err != nil {
logrus.Warnf("Unable to parse index URL: %s, skip...", u)
continue
}
if err := res.Pm.LoadPackageIndex(URL); err != nil {
res.PlatformIndexErrors = append(res.PlatformIndexErrors, err.Error())
}
}
if err := res.Pm.LoadHardware(); err != nil {
return res, fmt.Errorf("error loading hardware packages: %s", err)
}
}
if len(res.PlatformIndexErrors) == 0 {
res.PlatformIndexErrors = nil
}
// Initialize library manager
// --------------------------
res.Lm = librariesmanager.NewLibraryManager(dataDir, downloadsDir)
// Add IDE builtin libraries dir
if bundledLibsDir := configuration.IDEBundledLibrariesDir(); bundledLibsDir != nil {
res.Lm.AddLibrariesDir(bundledLibsDir, libraries.IDEBuiltIn)
}
// Add user libraries dir
libDir := configuration.LibrariesDir()
res.Lm.AddLibrariesDir(libDir, libraries.User)
// Add libraries dirs from installed platforms
if res.Pm != nil {
for _, targetPackage := range res.Pm.Packages {
for _, platform := range targetPackage.Platforms {
if platformRelease := res.Pm.GetInstalledPlatformRelease(platform); platformRelease != nil {
res.Lm.AddPlatformReleaseLibrariesDir(platformRelease, libraries.PlatformBuiltIn)
}
}
}
}
// Load index and auto-update it if needed
if err := res.Lm.LoadIndex(); err != nil {
res.LibrariesIndexError = err.Error()
}
// Scan for libraries
if err := res.Lm.RescanLibraries(); err != nil {
return res, fmt.Errorf("libraries rescan: %s", err)
}
return res, nil
}