diff --git a/api/datastore/mysql/mysql.go b/api/datastore/mysql/mysql.go index 5fe4a5fd..ec0b853b 100644 --- a/api/datastore/mysql/mysql.go +++ b/api/datastore/mysql/mysql.go @@ -23,6 +23,7 @@ const routesTableCreate = `CREATE TABLE IF NOT EXISTS routes ( maxc int NOT NULL, memory int NOT NULL, timeout int NOT NULL, + idle_timeout int NOT NULL, type varchar(16) NOT NULL, headers text NOT NULL, config text NOT NULL, @@ -39,7 +40,7 @@ const extrasTableCreate = `CREATE TABLE IF NOT EXISTS extras ( value varchar(256) NOT NULL );` -const routeSelector = `SELECT app_name, path, image, format, maxc, memory, type, timeout, headers, config FROM routes` +const routeSelector = `SELECT app_name, path, image, format, maxc, memory, type, timeout, idle_timeout, headers, config FROM routes` type rowScanner interface { Scan(dest ...interface{}) error @@ -302,10 +303,11 @@ func (ds *MySQLDatastore) InsertRoute(ctx context.Context, route *models.Route) memory, type, timeout, + idle_timeout, headers, config ) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?);`, + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);`, route.AppName, route.Path, route.Image, @@ -314,6 +316,7 @@ func (ds *MySQLDatastore) InsertRoute(ctx context.Context, route *models.Route) route.Memory, route.Type, route.Timeout, + route.IdleTimeout, string(hbyte), string(cbyte), ) @@ -359,6 +362,7 @@ func (ds *MySQLDatastore) UpdateRoute(ctx context.Context, newroute *models.Rout memory = ?, type = ?, timeout = ?, + idle_timeout = ?, headers = ?, config = ? WHERE app_name = ? AND path = ?;`, @@ -368,6 +372,7 @@ func (ds *MySQLDatastore) UpdateRoute(ctx context.Context, newroute *models.Rout route.Memory, route.Type, route.Timeout, + route.IdleTimeout, string(hbyte), string(cbyte), route.AppName, @@ -431,6 +436,7 @@ func scanRoute(scanner rowScanner, route *models.Route) error { &route.Memory, &route.Type, &route.Timeout, + &route.IdleTimeout, &headerStr, &configStr, ) diff --git a/api/datastore/postgres/postgres.go b/api/datastore/postgres/postgres.go index 3e2fe41d..794b7436 100644 --- a/api/datastore/postgres/postgres.go +++ b/api/datastore/postgres/postgres.go @@ -8,12 +8,12 @@ import ( "context" + "bytes" "github.com/Sirupsen/logrus" + "github.com/iron-io/functions/api/datastore/internal/datastoreutil" "github.com/iron-io/functions/api/models" "github.com/lib/pq" _ "github.com/lib/pq" - "bytes" - "github.com/iron-io/functions/api/datastore/internal/datastoreutil" ) const routesTableCreate = ` @@ -25,6 +25,7 @@ CREATE TABLE IF NOT EXISTS routes ( maxc integer NOT NULL, memory integer NOT NULL, timeout integer NOT NULL, + idle_timeout integer NOT NULL, type character varying(16) NOT NULL, headers text NOT NULL, config text NOT NULL, @@ -41,7 +42,7 @@ const extrasTableCreate = `CREATE TABLE IF NOT EXISTS extras ( value character varying(256) NOT NULL );` -const routeSelector = `SELECT app_name, path, image, format, maxc, memory, type, timeout, headers, config FROM routes` +const routeSelector = `SELECT app_name, path, image, format, maxc, memory, type, timeout, idle_timeout, headers, config FROM routes` type rowScanner interface { Scan(dest ...interface{}) error @@ -120,7 +121,7 @@ func (ds *PostgresDatastore) UpdateApp(ctx context.Context, newapp *models.App) return err } - if config != "" { + if len(config) > 0 { err := json.Unmarshal([]byte(config), &app.Config) if err != nil { return err @@ -184,8 +185,11 @@ func (ds *PostgresDatastore) GetApp(ctx context.Context, name string) (*models.A Name: resName, } - if err := json.Unmarshal([]byte(config), &res.Config); err != nil { - return nil, err + if len(config) > 0 { + err := json.Unmarshal([]byte(config), &res.Config) + if err != nil { + return nil, err + } } return res, nil @@ -202,7 +206,14 @@ func scanApp(scanner rowScanner, app *models.App) error { return err } - return json.Unmarshal([]byte(configStr), &app.Config) + if len(configStr) > 0 { + err = json.Unmarshal([]byte(configStr), &app.Config) + if err != nil { + return err + } + } + + return nil } func (ds *PostgresDatastore) GetApps(ctx context.Context, filter *models.AppFilter) ([]*models.App, error) { @@ -274,10 +285,11 @@ func (ds *PostgresDatastore) InsertRoute(ctx context.Context, route *models.Rout memory, type, timeout, + idle_timeout, headers, config ) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10);`, + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11);`, route.AppName, route.Path, route.Image, @@ -286,13 +298,13 @@ func (ds *PostgresDatastore) InsertRoute(ctx context.Context, route *models.Rout route.Memory, route.Type, route.Timeout, + route.IdleTimeout, string(hbyte), string(cbyte), ) return err }) - if err != nil { return nil, err } @@ -329,8 +341,9 @@ func (ds *PostgresDatastore) UpdateRoute(ctx context.Context, newroute *models.R memory = $6, type = $7, timeout = $8, - headers = $9, - config = $10 + idle_timeout = $9, + headers = $10, + config = $11 WHERE app_name = $1 AND path = $2;`, route.AppName, route.Path, @@ -340,6 +353,7 @@ func (ds *PostgresDatastore) UpdateRoute(ctx context.Context, newroute *models.R route.Memory, route.Type, route.Timeout, + route.IdleTimeout, string(hbyte), string(cbyte), ) @@ -398,6 +412,7 @@ func scanRoute(scanner rowScanner, route *models.Route) error { &route.Memory, &route.Type, &route.Timeout, + &route.IdleTimeout, &headerStr, &configStr, ) @@ -405,14 +420,21 @@ func scanRoute(scanner rowScanner, route *models.Route) error { return err } - if headerStr == "" { - return models.ErrRoutesNotFound + if len(headerStr) > 0 { + err = json.Unmarshal([]byte(headerStr), &route.Headers) + if err != nil { + return err + } } - if err := json.Unmarshal([]byte(headerStr), &route.Headers); err != nil { - return err + if len(configStr) > 0 { + err = json.Unmarshal([]byte(configStr), &route.Config) + if err != nil { + return err + } } - return json.Unmarshal([]byte(configStr), &route.Config) + + return nil } func (ds *PostgresDatastore) GetRoute(ctx context.Context, appName, routePath string) (*models.Route, error) { @@ -557,7 +579,6 @@ func (ds *PostgresDatastore) Get(ctx context.Context, key []byte) ([]byte, error return []byte(value), nil } - func (ds *PostgresDatastore) Tx(f func(*sql.Tx) error) error { tx, err := ds.db.Begin() if err != nil { diff --git a/api/models/new_task.go b/api/models/new_task.go index 41492916..248fd11d 100644 --- a/api/models/new_task.go +++ b/api/models/new_task.go @@ -54,6 +54,11 @@ type NewTask struct { */ Timeout *int32 `json:"timeout,omitempty"` + + /* Hot function idle timeout in seconds before termination. + + */ + IdleTimeout *int32 `json:"idle_timeout,omitempty"` } // Validate validates this new task diff --git a/api/models/route.go b/api/models/route.go index 372bb131..57faf691 100644 --- a/api/models/route.go +++ b/api/models/route.go @@ -12,6 +12,7 @@ import ( const ( defaultRouteTimeout = 30 // seconds + htfnScaleDownTimeout = 30 // seconds ) var ( @@ -39,6 +40,7 @@ type Route struct { Format string `json:"format"` MaxConcurrency int `json:"max_concurrency"` Timeout int32 `json:"timeout"` + IdleTimeout int32 `json:"idle_timeout"` Config `json:"config"` } @@ -54,6 +56,7 @@ var ( ErrRoutesValidationMissingType = errors.New("Missing route Type") ErrRoutesValidationPathMalformed = errors.New("Path malformed") ErrRoutesValidationNegativeTimeout = errors.New("Negative timeout") + ErrRoutesValidationNegativeIdleTimeout = errors.New("Negative idle timeout") ErrRoutesValidationNegativeMaxConcurrency = errors.New("Negative MaxConcurrency") ) @@ -86,6 +89,10 @@ func (r *Route) SetDefaults() { if r.Timeout == 0 { r.Timeout = defaultRouteTimeout } + + //if r.IdleTimeout == 0 { + // r.IdleTimeout = htfnScaleDownTimeout + //} } // Validate validates field values, skipping zeroed fields if skipZero is true. @@ -141,6 +148,10 @@ func (r *Route) Validate(skipZero bool) error { res = append(res, ErrRoutesValidationNegativeTimeout) } + if r.IdleTimeout < 0 { + res = append(res, ErrRoutesValidationNegativeIdleTimeout) + } + if len(res) > 0 { return apiErrors.CompositeValidationError(res...) } @@ -171,6 +182,9 @@ func (r *Route) Update(new *Route) { if new.Timeout != 0 { r.Timeout = new.Timeout } + if new.IdleTimeout != 0 { + r.IdleTimeout = new.IdleTimeout + } if new.Format != "" { r.Format = new.Format } diff --git a/api/runner/async_runner.go b/api/runner/async_runner.go index 1909e47f..af9df792 100644 --- a/api/runner/async_runner.go +++ b/api/runner/async_runner.go @@ -42,14 +42,18 @@ func getTask(ctx context.Context, url string) (*models.Task, error) { } func getCfg(t *models.Task) *task.Config { + timeout := int32(30) if t.Timeout == nil { - timeout := int32(30) t.Timeout = &timeout } + if t.IdleTimeout == nil { + t.IdleTimeout = &timeout + } cfg := &task.Config{ Image: *t.Image, Timeout: time.Duration(*t.Timeout) * time.Second, + IdleTimeout: time.Duration(*t.IdleTimeout) * time.Second, ID: t.ID, AppName: t.AppName, Env: t.EnvVars, diff --git a/api/runner/task.go b/api/runner/task.go index a54c5d6f..01b28ab6 100644 --- a/api/runner/task.go +++ b/api/runner/task.go @@ -35,7 +35,8 @@ func (t *containerTask) Id() string { return t.cfg.ID } func (t *containerTask) Route() string { return "" } func (t *containerTask) Image() string { return t.cfg.Image } func (t *containerTask) Timeout() time.Duration { return t.cfg.Timeout } -func (t *containerTask) Logger() (stdout, stderr io.Writer) { return t.cfg.Stdout, t.cfg.Stderr } +func (t *containerTask) IdleTimeout() time.Duration { return t.cfg.IdleTimeout } +func (t *containerTask) Logger() (io.Writer, io.Writer) { return t.cfg.Stdout, t.cfg.Stderr } func (t *containerTask) Volumes() [][2]string { return [][2]string{} } func (t *containerTask) WorkDir() string { return "" } diff --git a/api/runner/task/task.go b/api/runner/task/task.go index 1399d6c1..a7f7d24b 100644 --- a/api/runner/task/task.go +++ b/api/runner/task/task.go @@ -9,15 +9,16 @@ import ( ) type Config struct { - ID string - Path string - Image string - Timeout time.Duration - AppName string - Memory uint64 - Env map[string]string - Format string - MaxConcurrency int + ID string + Path string + Image string + Timeout time.Duration + IdleTimeout time.Duration + AppName string + Memory uint64 + Env map[string]string + Format string + MaxConcurrency int Stdin io.Reader Stdout io.Writer diff --git a/api/runner/worker.go b/api/runner/worker.go index 91c4ee61..4a97b4e8 100644 --- a/api/runner/worker.go +++ b/api/runner/worker.go @@ -61,10 +61,6 @@ import ( // Terminate // (internal clock) -const ( - // Terminate hot function after this timeout - htfnScaleDownTimeout = 30 * time.Second -) // RunTask helps sending a task.Request into the common concurrency stream. // Refer to StartWorkers() to understand what this is about. @@ -264,17 +260,29 @@ func newhtfn(cfg *task.Config, proto protocol.Protocol, tasks <-chan task.Reques func (hc *htfn) serve(ctx context.Context) { lctx, cancel := context.WithCancel(ctx) var wg sync.WaitGroup + cfg := *hc.cfg + logger := logrus.WithFields(logrus.Fields{ + "app": cfg.AppName, + "route": cfg.Path, + "image": cfg.Image, + "memory": cfg.Memory, + "format": cfg.Format, + "max_concurrency": cfg.MaxConcurrency, + "idle_timeout": cfg.IdleTimeout, + }) + wg.Add(1) go func() { defer wg.Done() for { - inactivity := time.After(htfnScaleDownTimeout) + inactivity := time.After(cfg.IdleTimeout) select { case <-lctx.Done(): return case <-inactivity: + logger.Info("Canceling inactive hot function") cancel() case t := <-hc.tasks: @@ -295,7 +303,6 @@ func (hc *htfn) serve(ctx context.Context) { } }() - cfg := *hc.cfg cfg.Env["FN_FORMAT"] = cfg.Format cfg.Timeout = 0 // add a timeout to simulate ab.end. failure. cfg.Stdin = hc.containerIn @@ -324,14 +331,7 @@ func (hc *htfn) serve(ctx context.Context) { defer wg.Done() scanner := bufio.NewScanner(errr) for scanner.Scan() { - logrus.WithFields(logrus.Fields{ - "app": cfg.AppName, - "route": cfg.Path, - "image": cfg.Image, - "memory": cfg.Memory, - "format": cfg.Format, - "max_concurrency": cfg.MaxConcurrency, - }).Info(scanner.Text()) + logger.Info(scanner.Text()) } }() @@ -339,7 +339,6 @@ func (hc *htfn) serve(ctx context.Context) { if err != nil { logrus.WithError(err).Error("hot function failure detected") } - cancel() errw.Close() wg.Wait() logrus.WithField("result", result).Info("hot function terminated") diff --git a/api/server/runner.go b/api/server/runner.go index 5de2b132..818222f5 100644 --- a/api/server/runner.go +++ b/api/server/runner.go @@ -190,17 +190,18 @@ func (s *Server) serve(ctx context.Context, c *gin.Context, appName string, foun } cfg := &task.Config{ - AppName: appName, - Path: found.Path, - Env: envVars, - Format: found.Format, - ID: reqID, - Image: found.Image, - MaxConcurrency: found.MaxConcurrency, - Memory: found.Memory, - Stdin: payload, - Stdout: &stdout, - Timeout: time.Duration(found.Timeout) * time.Second, + AppName: appName, + Path: found.Path, + Env: envVars, + Format: found.Format, + ID: reqID, + Image: found.Image, + MaxConcurrency: found.MaxConcurrency, + Memory: found.Memory, + Stdin: payload, + Stdout: &stdout, + Timeout: time.Duration(found.Timeout) * time.Second, + IdleTimeout: time.Duration(found.IdleTimeout) * time.Second, } s.Runner.Enqueue() diff --git a/api/version/version.go b/api/version/version.go index 780b5332..7c086d1d 100644 --- a/api/version/version.go +++ b/api/version/version.go @@ -1,4 +1,4 @@ package version // Version of IronFunctions -var Version = "0.2.54" +var Version = "0.2.57" diff --git a/docs/function-timeouts.md b/docs/function-timeouts.md new file mode 100644 index 00000000..4dd61350 --- /dev/null +++ b/docs/function-timeouts.md @@ -0,0 +1,58 @@ +# Function timeouts + +Within Function API, each functions supplied with 2 timeouts parameters, both optional, see [swagger.yaml](swagger.yml) for more details. +So, what are those timeouts and what are they used for? + +## Function call timeout + +This time of timeouts defines for how long function execution may happen before it'll be terminated along with notifying caller that function terminated with error - timed out. + +```json +{ + "route":{ + ... + "timeout": 30, + ... + } +} +``` + +This timeout parameter used with both types of functions: async and sync. +It starts at the beginning of function call. + +## Hot function idle timeout + +This type of timeout defines for how long should hot function hang around before its termination in case if there are no incoming requests. + +```json +{ + "route":{ + ... + "idle_timeout": 30, + ... + } +} +``` + +This timeout parameter is valid for hot functions, see what [hot functions](hot-functions.md) is. By default this parameter equals to 30 seconds. +It starts after last request being processed by hot function. + +## Correlation between idle and regular timeout + +This two timeouts are independent. The order of timeouts for hot functions: + + 0. start hot function be sending first timeout-bound request to it + 1. make request to function with `timeout` + 2. if call finished (no matter successful or not) check for more requests to dispatch + 3. if none - start idle timeout + 4. if new request appears - stop idle timeout and serve request + 5. if none - terminate hot function + +## Hot function idle timeout edge cases + +Having both timeouts may cause confusion while configuring hot function. +So, there are certain limitations for `idle_timeout` as well as for regular `timeout`: + + * Idle timeout might be equal to zero. Such case may lead to satiation when function would be terminated immediately after last request processing, i.e. no idle timeout at all. + * Idle timeout can't be negative. + * Idle timeout can't be changed while hot function is running. Idle timeout is permanent within hot function execution lifecycle. It means that idle timeout should be considered for changing once functions is not running. diff --git a/docs/hot-functions.md b/docs/hot-functions.md index dde40fdc..022d63db 100644 --- a/docs/hot-functions.md +++ b/docs/hot-functions.md @@ -91,7 +91,8 @@ requests: "type": "sync", "config": null, "format": "http", - "max_concurrency": "1" + "max_concurrency": "1", + "idle_timeout": 30 } } ``` @@ -100,4 +101,6 @@ requests: container. `max_concurrency` (optional) - the number of simultaneous hot functions for -this functions. This is a per-node configuration option. Default: 1 \ No newline at end of file +this functions. This is a per-node configuration option. Default: 1 + +`idle_timeout` (optional) - idle timeout (in seconds) before function termination. diff --git a/docs/swagger.yml b/docs/swagger.yml index 03c8db51..d9b32827 100644 --- a/docs/swagger.yml +++ b/docs/swagger.yml @@ -378,8 +378,12 @@ definitions: type: string timeout: type: integer - default: 60 + default: 30 description: Timeout for executions of this route. Value in Seconds + idle_timeout: + type: integer + default: 30 + description: Hot functions idle timeout before termination. Value in Seconds App: type: object diff --git a/examples/lambda/node/README.md b/examples/lambda/node/README.md index 640a0a91..9480dc46 100644 --- a/examples/lambda/node/README.md +++ b/examples/lambda/node/README.md @@ -2,12 +2,12 @@ This is the exact same function that is in the AWS Lambda tutorial. -Other than a different runtime, this is no different than any other node example. +Other than a different runtime, this is no different than any other node example. -To use the lambda-node runtime, use this `fn init` command: +To use the lambda-nodejs4.3 runtime, use this `fn init` command: ```sh -fn init --runtime lambda-node /lambda-node +fn init --runtime lambda-nodejs4.3 /lambda-node fn build cat payload.json | fn run ``` diff --git a/fn/chocolatey/functions.nuspec b/fn/chocolatey/functions.nuspec new file mode 100644 index 00000000..c65619b2 --- /dev/null +++ b/fn/chocolatey/functions.nuspec @@ -0,0 +1,21 @@ + + + + + functions + 0.2.57 + https://github.com/iron-io/functions + + Iron.io Functions (Install) + Iron.io Inc. + https://github.com/iron-io/functions + + 2017 Functions Iron.io + serverless functions faas docker lambda + IronFunctions - the serverless microservices platform. + IronFunctions is an open source serverless platform, or as we like to refer to it, Functions as a Service (FaaS) platform that you can run anywhere. + + + + + diff --git a/fn/chocolatey/tools/LICENSE.txt b/fn/chocolatey/tools/LICENSE.txt new file mode 100644 index 00000000..57129b3e --- /dev/null +++ b/fn/chocolatey/tools/LICENSE.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2016 Iron.io + + 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. \ No newline at end of file diff --git a/fn/chocolatey/tools/chocolateybeforemodify.ps1 b/fn/chocolatey/tools/chocolateybeforemodify.ps1 new file mode 100644 index 00000000..4519b402 --- /dev/null +++ b/fn/chocolatey/tools/chocolateybeforemodify.ps1 @@ -0,0 +1 @@ +# Do nothing yet \ No newline at end of file diff --git a/fn/chocolatey/tools/chocolateyinstall.ps1 b/fn/chocolatey/tools/chocolateyinstall.ps1 new file mode 100644 index 00000000..f07a5c05 --- /dev/null +++ b/fn/chocolatey/tools/chocolateyinstall.ps1 @@ -0,0 +1,24 @@ +$ErrorActionPreference = 'Stop'; + +$packageName= 'functions' +$toolsDir = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)" +$url = 'https://github.com/iron-io/functions/releases/download/0.2.57/fn.exe' +#$fileLocation = Join-Path $toolsDir 'NAME_OF_EMBEDDED_INSTALLER_FILE' +#$fileLocation = '\\SHARE_LOCATION\to\INSTALLER_FILE' + +$packageArgs = @{ + packageName = $packageName + unzipLocation = $toolsDir + fileType = 'EXE' + url = $url + #file = $fileLocation + + softwareName = 'Iron.io Functions*' + + checksum = 'D4E0628696732C8A237C6D88FC7D409551D4D223C4ED0752880673FAD6D33319' + checksumType = 'sha256' + + validExitCodes= @(0, 3010, 1641) +} + +Install-ChocolateyPackage @packageArgs \ No newline at end of file diff --git a/fn/common.go b/fn/common.go index 8e909d67..582a8bee 100644 --- a/fn/common.go +++ b/fn/common.go @@ -118,22 +118,22 @@ func exists(name string) bool { } var acceptableFnRuntimes = map[string]string{ - "elixir": "iron/elixir", - "erlang": "iron/erlang", - "gcc": "iron/gcc", - "go": "iron/go", - "java": "iron/java", - "leiningen": "iron/leiningen", - "mono": "iron/mono", - "node": "iron/node", - "perl": "iron/perl", - "php": "iron/php", - "python": "iron/python:2", - "ruby": "iron/ruby", - "scala": "iron/scala", - "rust": "corey/rust-alpine", - "dotnet": "microsoft/dotnet:runtime", - "lambda-node": "iron/functions-lambda:node", + "elixir": "iron/elixir", + "erlang": "iron/erlang", + "gcc": "iron/gcc", + "go": "iron/go", + "java": "iron/java", + "leiningen": "iron/leiningen", + "mono": "iron/mono", + "node": "iron/node", + "perl": "iron/perl", + "php": "iron/php", + "python": "iron/python:2", + "ruby": "iron/ruby", + "scala": "iron/scala", + "rust": "corey/rust-alpine", + "dotnet": "microsoft/dotnet:runtime", + "lambda-nodejs4.3": "iron/functions-lambda:nodejs4.3", } const tplDockerfile = `FROM {{ .BaseImage }} diff --git a/fn/install.sh b/fn/install.sh index 53524424..308434b1 100644 --- a/fn/install.sh +++ b/fn/install.sh @@ -3,7 +3,7 @@ set -e # Install script to install fn -release="0.2.54" +release="0.2.57" command_exists() { command -v "$@" > /dev/null 2>&1 diff --git a/fn/lambda.go b/fn/lambda.go index 6376f654..26d74b93 100644 --- a/fn/lambda.go +++ b/fn/lambda.go @@ -2,7 +2,6 @@ package main import ( "archive/zip" - "bytes" "errors" "fmt" "io" @@ -17,16 +16,12 @@ import ( "github.com/aws/aws-sdk-go/aws/session" aws_lambda "github.com/aws/aws-sdk-go/service/lambda" "github.com/docker/docker/pkg/jsonmessage" - lambdaImpl "github.com/iron-io/lambda/lambda" "github.com/urfave/cli" yaml "gopkg.in/yaml.v2" ) -func init() { - if len(runtimeCreateHandlers) != len(runtimeImportHandlers) { - panic("incomplete implementation of runtime support") - } - +var runtimes = map[string]string{ + "nodejs4.3": "lambda-nodejs4.3", } func lambda() cli.Command { @@ -38,20 +33,6 @@ func lambda() cli.Command { Name: "lambda", Usage: "create and publish lambda functions", Subcommands: []cli.Command{ - { - Name: "create-function", - Usage: `create Docker image that can run your Lambda function, where files are the contents of the zip file to be uploaded to AWS Lambda.`, - ArgsUsage: " [/paths...]", - Action: create, - Flags: flags, - }, - { - Name: "test-function", - Usage: `runs local dockerized Lambda function and writes output to stdout.`, - ArgsUsage: "", - Action: test, - Flags: flags, - }, { 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.`, @@ -100,87 +81,6 @@ func transcribeEnvConfig(configs []string) map[string]string { return c } -// create creates the Docker image for the Lambda function -func create(c *cli.Context) error { - args := c.Args() - functionName := args[0] - runtime := args[1] - handler := args[2] - fileNames := args[3:] - - files := make([]fileLike, 0, len(fileNames)) - opts := createImageOptions{ - Name: functionName, - Base: fmt.Sprintf("iron/lambda-%s", runtime), - Package: "", - Handler: handler, - OutputStream: newdockerJSONWriter(os.Stdout), - RawJSONStream: true, - Config: transcribeEnvConfig(c.StringSlice("config")), - } - - if handler == "" { - return errors.New("No handler specified.") - } - - rh, ok := runtimeCreateHandlers[runtime] - if !ok { - return fmt.Errorf("unsupported runtime %v", runtime) - } - - if err := rh(fileNames, &opts); err != nil { - return err - } - - for _, fileName := range fileNames { - file, err := os.Open(fileName) - if err != nil { - return err - } - defer file.Close() - files = append(files, file) - } - - return createDockerfile(opts, files...) -} - -var runtimeCreateHandlers = map[string]func(filenames []string, opts *createImageOptions) error{ - "nodejs": func(filenames []string, opts *createImageOptions) error { return nil }, - "python2.7": func(filenames []string, opts *createImageOptions) error { return nil }, - "java8": func(filenames []string, opts *createImageOptions) error { - if len(filenames) != 1 { - return errors.New("Java Lambda functions can only include 1 file and it must be a JAR file.") - } - - if filepath.Ext(filenames[0]) != ".jar" { - return errors.New("Java Lambda function package must be a JAR file.") - } - - opts.Package = filepath.Base(filenames[0]) - return nil - }, -} - -func test(c *cli.Context) error { - args := c.Args() - if len(args) < 1 { - return fmt.Errorf("Missing NAME argument") - } - functionName := args[0] - - exists, err := lambdaImpl.ImageExists(functionName) - if err != nil { - return err - } - if !exists { - return fmt.Errorf("Function %s does not exist.", functionName) - } - - payload := c.String("payload") - // Redirect output to stdout. - return lambdaImpl.RunImageWithPayload(functionName, payload) -} - func awsImport(c *cli.Context) error { args := c.Args() @@ -216,7 +116,7 @@ func awsImport(c *cli.Context) error { opts := createImageOptions{ Name: functionName, - Base: fmt.Sprintf("iron/lambda-%s", *function.Configuration.Runtime), + Base: runtimes[(*function.Configuration.Runtime)], Package: "", Handler: *function.Configuration.Handler, OutputStream: newdockerJSONWriter(os.Stdout), @@ -230,7 +130,7 @@ func awsImport(c *cli.Context) error { return fmt.Errorf("unsupported runtime %v", runtime) } - files, err := rh(functionName, tmpFileName, &opts) + _, err = rh(functionName, tmpFileName, &opts) if err != nil { return nil } @@ -239,12 +139,18 @@ func awsImport(c *cli.Context) error { opts.Name = image } - return createDockerfile(opts, files...) + 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){ - "nodejs": basicImportHandler, + "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.") @@ -268,20 +174,25 @@ func basicImportHandler(functionName, tmpFileName string, opts *createImageOptio return unzipAndGetTopLevelFiles(functionName, tmpFileName) } -func createFunctionYaml(opts createImageOptions) error { +func createFunctionYaml(opts createImageOptions, functionName string) error { strs := strings.Split(opts.Name, "/") path := fmt.Sprintf("/%s", strs[1]) + funcDesc := &funcfile{ - Name: opts.Name, - Path: &path, - Config: opts.Config, + Name: opts.Name, + Path: &path, + Config: opts.Config, + Version: "0.0.1", + Runtime: &opts.Base, + Cmd: opts.Handler, } out, err := yaml.Marshal(funcDesc) if err != nil { return err } - return ioutil.WriteFile(filepath.Join(opts.Name, "func.yaml"), out, 0644) + + return ioutil.WriteFile(filepath.Join(functionName, "func.yaml"), out, 0644) } type createImageOptions struct { @@ -301,90 +212,6 @@ type fileLike interface { var errNoFiles = errors.New("No files to add to image") -// Create a Dockerfile that adds each of the files to the base image. The -// expectation is that the base image sets up the current working directory -// inside the image correctly. `handler` is set to be passed to node-lambda -// for now, but we may have to change this to accomodate other stacks. -func makeDockerfile(base string, pkg string, handler string, files ...fileLike) ([]byte, error) { - var buf bytes.Buffer - fmt.Fprintf(&buf, "FROM %s\n", base) - - for _, file := range files { - // FIXME(nikhil): Validate path, no parent paths etc. - info, err := file.Stat() - if err != nil { - return buf.Bytes(), err - } - - fmt.Fprintf(&buf, "ADD [\"%s\", \"./%s\"]\n", info.Name(), info.Name()) - } - - fmt.Fprint(&buf, "CMD [") - if pkg != "" { - fmt.Fprintf(&buf, "\"%s\", ", pkg) - } - // FIXME(nikhil): Validate handler. - fmt.Fprintf(&buf, `"%s"`, handler) - fmt.Fprint(&buf, "]\n") - - return buf.Bytes(), nil -} - -// Creates a docker image called `name`, using `base` as the base image. -// `handler` is the runtime-specific name to use for a lambda invocation (i.e. -// . for nodejs). `files` should be a list of files+dirs -// *relative to the current directory* that are to be included in the image. -func createDockerfile(opts createImageOptions, files ...fileLike) error { - if len(files) == 0 { - return errNoFiles - } - - df, err := makeDockerfile(opts.Base, opts.Package, opts.Handler, files...) - if err != nil { - return err - } - - fmt.Printf("Creating directory: %s ... ", opts.Name) - if err := os.MkdirAll(opts.Name, os.ModePerm); err != nil { - return err - } - fmt.Println("OK") - - fmt.Printf("Creating Dockerfile: %s ... ", filepath.Join(opts.Name, "Dockerfile")) - outputFile, err := os.Create(filepath.Join(opts.Name, "Dockerfile")) - if err != nil { - return err - } - fmt.Println("OK") - - for _, f := range files { - fstat, err := f.Stat() - if err != nil { - return err - } - fmt.Printf("Copying file: %s ... ", filepath.Join(opts.Name, fstat.Name())) - src, err := os.Create(filepath.Join(opts.Name, fstat.Name())) - if err != nil { - return err - } - if _, err := io.Copy(src, f); err != nil { - return err - } - fmt.Println("OK") - } - - if _, err = outputFile.Write(df); err != nil { - return err - } - - fmt.Print("Creating func.yaml ... ") - if err := createFunctionYaml(opts); err != nil { - return err - } - fmt.Println("OK") - return nil -} - type dockerJSONWriter struct { under io.Writer w io.Writer diff --git a/fn/lambda/node/build.sh b/fn/lambda/node/build.sh index d6acaef0..140faa7a 100755 --- a/fn/lambda/node/build.sh +++ b/fn/lambda/node/build.sh @@ -1,3 +1,3 @@ set -ex -docker build -t iron/functions-lambda:node4.3 . +docker build -t iron/functions-lambda:nodejs4.3 . diff --git a/fn/lambda/node/release.sh b/fn/lambda/node/release.sh index 3ba1107e..313898f5 100755 --- a/fn/lambda/node/release.sh +++ b/fn/lambda/node/release.sh @@ -1,4 +1,4 @@ set -ex ./build.sh -docker push iron/functions-lambda:node4.3 +docker push iron/functions-lambda:nodejs4.3 diff --git a/fn/langs/base.go b/fn/langs/base.go index 16585b74..606402f7 100644 --- a/fn/langs/base.go +++ b/fn/langs/base.go @@ -15,7 +15,7 @@ func GetLangHelper(lang string) LangHelper { return &RustLangHelper{} case "dotnet": return &DotNetLangHelper{} - case "lambda-node": + case "lambda-nodejs4.3": return &LambdaNodeHelper{} } return nil diff --git a/release.sh b/release.sh index ef51e231..ab724f13 100755 --- a/release.sh +++ b/release.sh @@ -4,6 +4,10 @@ set -ex user="iron" service="functions" version_file="api/version/version.go" +# Chocolatey specific files +chocolatey_spec_file="fn/chocolatey/functions.nuspec" +chocolatey_install_file="fn/chocolatey/tools/chocolateyinstall.ps1" + tag="latest" if [ -z $(grep -m1 -Eo "[0-9]+\.[0-9]+\.[0-9]+" $version_file) ]; then @@ -15,6 +19,12 @@ perl -i -pe 's/\d+\.\d+\.\K(\d+)/$1+1/e' $version_file version=$(grep -m1 -Eo "[0-9]+\.[0-9]+\.[0-9]+" $version_file) echo "Version: $version" +# Update chocolatey version +sed 's|.*|'$version'|' $chocolatey_spec_file > "$chocolatey_spec_file.tmp" +mv "$chocolatey_spec_file.tmp" $chocolatey_spec_file +sed 's|https://github.com/iron-io/functions/releases/download/.*/fn.exe|https://github.com/iron-io/functions/releases/download/'$version'/fn.exe|' $chocolatey_install_file > "$chocolatey_install_file.tmp" +mv "$chocolatey_install_file.tmp" $chocolatey_install_file + make docker-build sed "s/release=.*/release=\"$version\"/g" fn/install.sh > fn/install.sh.tmp