GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — cli/lambda.go at master · appoxy/cli Expand file tree/ Copy pathlambda.goMore file actions 340 lines (293 loc) · 7.93 KB / Copy pathlambda.goFile metadata and controls340 lines (293 loc) · 7.93 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 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 package main import ( "archive/zip" "errors" "fmt" "io" "io/ioutil" "net/http" "os" "path/filepath" "strings" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/session" aws_lambda "github.com/aws/aws-sdk-go/service/lambda" "github.com/moby/moby/pkg/jsonmessage" "github.com/urfave/cli" yaml "gopkg.in/yaml.v2" ) var runtimes = map[string]string{ "nodejs4.3": "lambda-nodejs4.3", } func lambda() cli.Command { var flags []cli.Flag flags = append(flags, getFlags()...) return cli.Command{ Name: "lambda", Usage: "create and publish lambda functions", Subcommands: []cli.Command{ { Name: "aws-import", Usage: `converts an existing Lambda function to an image, where the function code is downloaded to a directory in the current working directory that has the same name as the Lambda function.`, ArgsUsage: "<arn> <region> <image/name>", Action: awsImport, Flags: flags, }, }, } } func getFlags() []cli.Flag { return []cli.Flag{ cli.StringFlag{ Name: "payload", Usage: "Payload to pass to the Lambda function. This is usually a JSON object.", Value: "{}", }, cli.StringFlag{ Name: "version", Usage: "Version of the function to import.", Value: "$LATEST", }, cli.BoolFlag{ Name: "download-only", Usage: "Only download the function into a directory. Will not create a Docker image.", }, cli.StringSliceFlag{ Name: "config", Usage: "function configuration", }, } } func transcribeEnvConfig(configs []string) map[string]string { c := make(map[string]string) for _, v := range configs { kv := strings.SplitN(v, "=", 2) if len(kv) == 1 { // TODO: Make sure it is compatible cross platform c[kv[0]] = fmt.Sprintf("$%s", kv[0]) } else { c[kv[0]] = kv[1] } } return c } func awsImport(c *cli.Context) error { args := c.Args() version := c.String("version") downloadOnly := c.Bool("download-only") profile := c.String("profile") arn := args[0] region := args[1] image := args[2] function, err := getFunction(profile, region, version, arn) if err != nil { return err } functionName := *function.Configuration.FunctionName err = os.Mkdir(fmt.Sprintf("./%s", functionName), os.ModePerm) if err != nil { return err } tmpFileName, err := downloadToFile(*function.Code.Location) if err != nil { return err } defer os.Remove(tmpFileName) if downloadOnly { // Since we are a command line program that will quit soon, it is OK to // let the OS clean `files` up. return err } opts := createImageOptions{ Name: functionName, Base: runtimes[(*function.Configuration.Runtime)], Package: "", Handler: *function.Configuration.Handler, OutputStream: newdockerJSONWriter(os.Stdout), RawJSONStream: true, Config: transcribeEnvConfig(c.StringSlice("config")), } runtime := *function.Configuration.Runtime rh, ok := runtimeImportHandlers[runtime] if !ok { return fmt.Errorf("unsupported runtime %v", runtime) } _, err = rh(functionName, tmpFileName, &opts) if err != nil { return nil } if image != "" { opts.Name = image } fmt.Print("Creating func.yaml ... ") if err := createFunctionYaml(opts, functionName); err != nil { return err } fmt.Println("OK") return nil } var ( runtimeImportHandlers = map[string]func(functionName, tmpFileName string, opts *createImageOptions) ([]fileLike, error){ "nodejs4.3": basicImportHandler, "python2.7": basicImportHandler, "java8": func(functionName, tmpFileName string, opts *createImageOptions) ([]fileLike, error) { fmt.Println("Found Java Lambda function. Going to assume code is a single JAR file.") path := filepath.Join(functionName, "function.jar") if err := os.Rename(tmpFileName, path); err != nil { return nil, err } fd, err := os.Open(path) if err != nil { return nil, err } files := []fileLike{fd} opts.Package = filepath.Base(files[0].(*os.File).Name()) return files, nil }, } ) func basicImportHandler(functionName, tmpFileName string, opts *createImageOptions) ([]fileLike, error) { return unzipAndGetTopLevelFiles(functionName, tmpFileName) } func createFunctionYaml(opts createImageOptions, functionName string) error { strs := strings.Split(opts.Name, "/") path := fmt.Sprintf("/%s", strs[1]) funcDesc := &funcfile{ Name: opts.Name, Version: "0.0.1", Runtime: opts.Base, Cmd: opts.Handler, } funcDesc.Config = opts.Config funcDesc.Path = path out, err := yaml.Marshal(funcDesc) if err != nil { return err } return ioutil.WriteFile(filepath.Join(functionName, "func.yaml"), out, 0644) } type createImageOptions struct { Name string Base string Package string // Used for Java, empty string for others. Handler string OutputStream io.Writer RawJSONStream bool Config map[string]string } type fileLike interface { io.Reader Stat() (os.FileInfo, error) } var errNoFiles = errors.New("No files to add to image") type dockerJSONWriter struct { under io.Writer w io.Writer } func newdockerJSONWriter(under io.Writer) *dockerJSONWriter { r, w := io.Pipe() go func() { err := jsonmessage.DisplayJSONMessagesStream(r, under, 1, true, nil) if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } }() return &dockerJSONWriter{under, w} } func (djw *dockerJSONWriter) Write(p []byte) (int, error) { return djw.w.Write(p) } func downloadToFile(url string) (string, error) { downloadResp, err := http.Get(url) if err != nil { return "", err } defer downloadResp.Body.Close() // zip reader needs ReaderAt, hence the indirection. tmpFile, err := ioutil.TempFile("", "lambda-function-") if err != nil { return "", err } if _, err := io.Copy(tmpFile, downloadResp.Body); err != nil { return "", err } if err := tmpFile.Close(); err != nil { return "", err } return tmpFile.Name(), nil } func unzipAndGetTopLevelFiles(dst, src string) (files []fileLike, topErr error) { files = make([]fileLike, 0) zipReader, err := zip.OpenReader(src) if err != nil { return files, err } defer zipReader.Close() var fd *os.File for _, f := range zipReader.File { path := filepath.Join(dst, f.Name) fmt.Printf("Extracting '%s' to '%s'\n", f.Name, path) if f.FileInfo().IsDir() { if err := os.Mkdir(path, 0644); err != nil { return nil, err } // Only top-level dirs go into the list since that is what CreateImage expects. if filepath.Dir(f.Name) == filepath.Base(f.Name) { fd, topErr = os.Open(path) if topErr != nil { break } files = append(files, fd) } } else { // We do not close fd here since we may want to use it to dockerize. fd, topErr = os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0644) if topErr != nil { break } var zipFd io.ReadCloser zipFd, topErr = f.Open() if topErr != nil { break } if _, topErr = io.Copy(fd, zipFd); topErr != nil { // OK to skip closing fd here. break } if err := zipFd.Close(); err != nil { return nil, err } // Only top-level files go into the list since that is what CreateImage expects. if filepath.Dir(f.Name) == "." { if _, topErr = fd.Seek(0, 0); topErr != nil { break } files = append(files, fd) } else { if err := fd.Close(); err != nil { return nil, err } } } } return } func getFunction(awsProfile, awsRegion, version, arn string) (*aws_lambda.GetFunctionOutput, error) { creds := credentials.NewChainCredentials([]credentials.Provider{ &credentials.EnvProvider{}, &credentials.SharedCredentialsProvider{ Filename: "", // Look in default location. Profile: awsProfile, }, }) conf := aws.NewConfig().WithCredentials(creds).WithCredentialsChainVerboseErrors(true).WithRegion(awsRegion) sess := session.New(conf) conn := aws_lambda.New(sess) resp, err := conn.GetFunction(&aws_lambda.GetFunctionInput{ FunctionName: aws.String(arn), Qualifier: aws.String(version), }) return resp, err } |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |