forked from open-lambda/open-lambda
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandlerPuller.go
More file actions
229 lines (192 loc) · 5.75 KB
/
Copy pathhandlerPuller.go
File metadata and controls
229 lines (192 loc) · 5.75 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
package lambda
import (
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"sync"
"github.com/open-lambda/open-lambda/ol/common"
)
var notFound404 = errors.New("file does not exist")
// TODO: for web registries, support an HTTP-based access key
// (https://en.wikipedia.org/wiki/Basic_access_authentication)
type HandlerPuller struct {
prefix string // combine with name to get file path or URL
dirCache sync.Map // key=lambda name, value=version, directory path
dirMaker *common.DirMaker
}
type CacheEntry struct {
version string // could be a timestamp for a file or web resource
path string // where code is extracted to a dir
}
func NewHandlerPuller(dirMaker *common.DirMaker) (cp *HandlerPuller, err error) {
return &HandlerPuller{
prefix: common.Conf.Registry,
dirMaker: dirMaker,
}, nil
}
func (cp *HandlerPuller) isRemote() bool {
return strings.HasPrefix(cp.prefix, "http://") || strings.HasPrefix(cp.prefix, "https://")
}
func (cp *HandlerPuller) Pull(name string) (targetDir string, err error) {
t := common.T0("pull-lambda")
defer t.T1()
matched, err := regexp.MatchString(`^[A-Za-z0-9\.\-\_]+$`, name)
if err != nil {
return "", err
} else if !matched {
msg := "bad lambda name '%s', can only contain letters, numbers, period, dash, and underscore"
return "", fmt.Errorf(msg, name)
}
if cp.isRemote() {
// registry type = web
urls := []string{
cp.prefix + "/" + name + ".tar.gz",
cp.prefix + "/" + name + ".py",
}
for i := 0; i < len(urls); i++ {
targetDir, err = cp.pullRemoteFile(urls[i], name)
if err == nil {
return targetDir, nil
} else if err != notFound404 {
// 404 is OK, because we just go on to check the next URLs
return "", err
}
}
return "", fmt.Errorf("lambda not found at any of these locations: %s", strings.Join(urls, ", "))
} else {
// registry type = file
paths := []string{
filepath.Join(cp.prefix, name) + ".tar.gz",
filepath.Join(cp.prefix, name) + ".py",
filepath.Join(cp.prefix, name),
}
for i := 0; i < len(paths); i++ {
if _, err := os.Stat(paths[i]); !os.IsNotExist(err) {
targetDir, err = cp.pullLocalFile(paths[i], name)
return targetDir, err
}
}
return "", fmt.Errorf("lambda not found at any of these locations: %s", strings.Join(paths, ", "))
}
}
// delete any caching associated with this handler
func (cp *HandlerPuller) Reset(name string) {
cp.dirCache.Delete(name)
}
func (cp *HandlerPuller) pullLocalFile(src, lambdaName string) (targetDir string, err error) {
stat, err := os.Stat(src)
if err != nil {
return "", err
}
if stat.Mode().IsDir() {
// this is really just a debug mode, and is not
// expected to be efficient
targetDir = cp.dirMaker.Get(lambdaName)
cmd := exec.Command("cp", "-r", src, targetDir)
if output, err := cmd.CombinedOutput(); err != nil {
return "", fmt.Errorf("%s :: %s", err, string(output))
}
return targetDir, nil
} else if !stat.Mode().IsRegular() {
return "", fmt.Errorf("%s not a file or directory", src)
}
// for regular files, we cache based on mod time. We don't
// cache at the file level if this is a remote store (because
// caching is handled at the web level)
version := stat.ModTime().String()
if !cp.isRemote() {
cacheEntry := cp.getCache(lambdaName)
if cacheEntry != nil && cacheEntry.version == version {
// hit:
return cacheEntry.path, nil
}
}
// miss:
targetDir = cp.dirMaker.Get(lambdaName)
if err := os.Mkdir(targetDir, os.ModeDir|0o700); err != nil {
return "", err
}
if strings.HasSuffix(src, ".py") {
cmd := exec.Command("cp", src, filepath.Join(targetDir, "f.py"))
if output, err := cmd.CombinedOutput(); err != nil {
return "", fmt.Errorf("%s :: %s", err, string(output))
}
} else if strings.HasSuffix(src, ".tar.gz") {
cmd := exec.Command("tar", "-xzf", src, "--directory", targetDir)
if output, err := cmd.CombinedOutput(); err != nil {
return "", fmt.Errorf("%s :: %s", err, string(output))
}
} else {
return "", fmt.Errorf("lambda file %s not a .ta.rgz or .py", src)
}
if !cp.isRemote() {
cp.putCache(lambdaName, version, targetDir)
}
return targetDir, nil
}
func (cp *HandlerPuller) pullRemoteFile(src, lambdaName string) (targetDir string, err error) {
// grab latest lambda code if it's changed (pass
// If-Modified-Since so this can be determined on server side
client := &http.Client{}
req, err := http.NewRequest("GET", src, nil)
if err != nil {
return "", err
}
cacheEntry := cp.getCache(lambdaName)
if cacheEntry != nil {
req.Header.Set("If-Modified-Since", cacheEntry.version)
}
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
return "", notFound404
}
if resp.StatusCode == http.StatusNotModified {
return cacheEntry.path, nil
}
// download to local file, then use pullLocalFile to finish
dir, err := ioutil.TempDir("", "ol-")
if err != nil {
return "", err
}
defer os.RemoveAll(dir)
parts := strings.Split(src, "/")
localPath := filepath.Join(dir, parts[len(parts)-1])
out, err := os.Create(localPath)
if err != nil {
return "", err
}
defer out.Close()
if _, err = io.Copy(out, resp.Body); err != nil {
return "", err
}
targetDir, err = cp.pullLocalFile(localPath, lambdaName)
// record directory in cache, by mod time
if err == nil {
version := resp.Header.Get("Last-Modified")
if version != "" {
cp.putCache(lambdaName, version, targetDir)
}
}
return targetDir, err
}
func (cp *HandlerPuller) getCache(name string) *CacheEntry {
entry, found := cp.dirCache.Load(name)
if !found {
return nil
}
return entry.(*CacheEntry)
}
func (cp *HandlerPuller) putCache(name, version, path string) {
cp.dirCache.Store(name, &CacheEntry{version, path})
}