forked from asteris-llc/converge
/
nodes.go
109 lines (90 loc) · 2.63 KB
/
nodes.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
// Copyright © 2016 Asteris, LLC
//
// 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 load
import (
"bytes"
"context"
"fmt"
"github.com/asteris-llc/converge/fetch"
"github.com/asteris-llc/converge/graph"
"github.com/asteris-llc/converge/helpers/logging"
"github.com/asteris-llc/converge/keystore"
"github.com/asteris-llc/converge/parse"
"github.com/pkg/errors"
)
type source struct {
Parent string
ParentSource string
Source string
}
func (s *source) String() string {
return fmt.Sprintf("%s (%s)", s.Source, s.Parent)
}
// Nodes loads and parses all resources referred to by the provided url
func Nodes(ctx context.Context, root string, verify bool) (*graph.Graph, error) {
logger := logging.GetLogger(ctx).WithField("function", "Nodes")
toLoad := []*source{{"root", root, root}}
out := graph.New()
out.Add("root", nil)
for len(toLoad) > 0 {
select {
case <-ctx.Done():
return nil, errors.New("interrupted")
default:
}
current := toLoad[0]
toLoad = toLoad[1:]
url, err := fetch.ResolveInContext(current.Source, current.ParentSource)
if err != nil {
return nil, err
}
logger.WithField("url", url).Debug("fetching")
content, err := fetch.Any(ctx, url)
if err != nil {
return nil, errors.Wrap(err, url)
}
if verify {
signatureURL := url + ".asc"
logger.WithField("signatureUrl", signatureURL).Debug("fetching")
signature, err := fetch.Any(ctx, signatureURL)
if err != nil {
return nil, errors.Wrap(err, signatureURL)
}
err = keystore.Default().CheckSignature(bytes.NewBuffer(content), bytes.NewBuffer(signature))
if err != nil {
return nil, errors.Wrap(err, signatureURL)
}
}
resources, err := parse.Parse(content)
if err != nil {
return nil, errors.Wrap(err, url)
}
for _, resource := range resources {
newID := graph.ID(current.Parent, resource.String())
out.Add(newID, resource)
out.ConnectParent(current.Parent, newID)
if resource.IsModule() {
toLoad = append(
toLoad,
&source{
Parent: newID,
ParentSource: url,
Source: resource.Source(),
},
)
}
}
}
return out, out.Validate()
}