mirror of
https://github.com/openfaas/faasd.git
synced 2025-06-18 12:06:36 +00:00
Compare commits
16 Commits
Author | SHA1 | Date | |
---|---|---|---|
8fbdd1a461 | |||
8dd48b8957 | |||
6763ed6d66 | |||
acb5d0bd1c | |||
2c9eb3904e | |||
b42066d1a1 | |||
17188b8de9 | |||
0c0088e8b0 | |||
c5f167df21 | |||
d5fcc7b2ab | |||
cbfefb6fa5 | |||
ea62c1b12d | |||
8f40618a5c | |||
3fe0d8d8d3 | |||
5aa4c69e03 | |||
12b5e8ca7f |
@ -1,5 +1,6 @@
|
||||
# faasd - a lightweight & portable faas engine
|
||||
|
||||
[](https://github.com/sponsors/openfaas)
|
||||
[](https://github.com/openfaas/faasd/actions)
|
||||
[](https://opensource.org/licenses/MIT)
|
||||
[](https://www.openfaas.com)
|
||||
@ -44,7 +45,7 @@ Additional resources:
|
||||
|
||||
Most importantly, it's easy to manage so you can set it up and leave it alone to run your functions.
|
||||
|
||||

|
||||
[](https://www.youtube.com/watch?v=WX1tZoSXy8E)
|
||||
|
||||
> Demo of faasd running asynchronous functions
|
||||
|
||||
@ -166,4 +167,6 @@ For completed features, WIP and upcoming roadmap see:
|
||||
|
||||
See [ROADMAP.md](docs/ROADMAP.md)
|
||||
|
||||
Want to build a patch without setting up a complete development environment? See [docs/PATCHES.md](docs/PATCHES.md)
|
||||
|
||||
Are you looking to hack on faasd? Follow the [developer instructions](docs/DEV.md) for a manual installation, or use the `hack/install.sh` script and pick up from there.
|
||||
|
@ -88,7 +88,7 @@ func makeProviderCmd() *cobra.Command {
|
||||
baseUserSecretsPath := path.Join(wd, "secrets")
|
||||
if err := moveSecretsToDefaultNamespaceSecrets(
|
||||
baseUserSecretsPath,
|
||||
faasd.FunctionNamespace); err != nil {
|
||||
faasd.DefaultFunctionNamespace); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
|
@ -1,7 +1,11 @@
|
||||
## Instructions for hacking on faasd itself
|
||||
## Instructions for building and testing faasd locally
|
||||
|
||||
> Note: if you're just wanting to try out faasd, then it's likely that you're on the wrong page. This is a detailed set of instructions for those wanting to contribute or customise faasd. Feel free to go back to the homepage and pick a tutorial instead.
|
||||
|
||||
Do you want to help the community test a pull request?
|
||||
|
||||
See these instructions instead: [Testing patches](/docs/PATCHES.md)
|
||||
|
||||
### Pre-reqs
|
||||
|
||||
> It's recommended that you do not install Docker on the same host as faasd, since 1) they may both use different versions of containerd and 2) docker's networking rules can disrupt faasd's networking. When using faasd - make your faasd server a faasd server, and build container image on your laptop or in a CI pipeline.
|
||||
|
88
docs/PATCHES.md
Normal file
88
docs/PATCHES.md
Normal file
@ -0,0 +1,88 @@
|
||||
## Instructions for testing a patch for faasd
|
||||
|
||||
### Launch a virtual machine
|
||||
|
||||
You can use any kind of Linux virtual machine, Ubuntu 20.04 is recommended.
|
||||
|
||||
Launch a cloud VM or use [Multipass](https://multipass.run), which is free to use an can be run locally. A Raspberry Pi 3 or 4 could also be used, but will need you to run `make dist` to cross compile a valid binary.
|
||||
|
||||
### Copy over your SSH key
|
||||
|
||||
Your SSH key will be used, so that you can copy a new faasd binary over to the host.
|
||||
|
||||
```bash
|
||||
multipass launch \
|
||||
--mem 4G \
|
||||
-c 2 \
|
||||
-n faasd
|
||||
|
||||
# Then access its shell
|
||||
multipass shell faasd
|
||||
|
||||
# Edit .ssh/authorized_keys
|
||||
|
||||
# Add .ssh/id_rsa.pub from your host and save the file
|
||||
```
|
||||
|
||||
### Install faasd on the VM
|
||||
|
||||
You start off with the upstream version of faasd on the host, then add the new version over the top later on.
|
||||
|
||||
```bash
|
||||
cd /tmp/
|
||||
git clone https://github.com/openfaas/faasd --depth=1
|
||||
cd faasd/hack
|
||||
./install.sh
|
||||
|
||||
# Run the login command given to you at the end of the script
|
||||
```
|
||||
|
||||
Get the multipass IP address:
|
||||
|
||||
```bash
|
||||
export IP=$(multipass info faasd --format json| jq -r '.info.faasd.ipv4[0]')
|
||||
```
|
||||
|
||||
### Build a new faasd binary with the patch
|
||||
|
||||
Check out faasd on your local computer
|
||||
|
||||
```bash
|
||||
git clone https://github.com/openfaas/faasd
|
||||
cd faasd
|
||||
|
||||
gh pr checkout #PR_NUMBER_HERE
|
||||
|
||||
GOOS=linux go build
|
||||
|
||||
# You can also run "make dist" which is slower, but includes
|
||||
# a version and binaries for other platforms such as the Raspberry Pi
|
||||
```
|
||||
|
||||
### Copy it over to the VM
|
||||
|
||||
Now build a new faasd binary and copy it to the VM:
|
||||
|
||||
```bash
|
||||
scp faasd ubuntu@$IP:~/
|
||||
```
|
||||
|
||||
Now deploy the new version on the VM:
|
||||
|
||||
```bash
|
||||
killall -9 faasd-linux; killall -9 faasd-linux ; mv ./faasd-linux /usr/local/bin/faasd
|
||||
```
|
||||
|
||||
### Check it worked and test that patch
|
||||
|
||||
Now run a command with `faas-cli` such as:
|
||||
|
||||
* `faas-cli list`
|
||||
* `faas-cli version`
|
||||
|
||||
See the testing instructions on the PR and run through those steps.
|
||||
|
||||
Post your results on GitHub to assist the creator of the pull request.
|
||||
|
||||
You can see how to get the logs for various components using the [eBook Serverless For Everyone Else](https://gumroad.com/l/serverless-for-everyone-else), or by consulting the [DEV.md](/docs/DEV.md) guide.
|
||||
|
@ -75,10 +75,10 @@ sudo systemctl restart faasd
|
||||
|
||||
Should have:
|
||||
|
||||
* [ ] Resolve core services from functions by populating/sharing `/etc/hosts` between `faasd` and `faasd-provider`
|
||||
* [ ] Docs or examples on how to use the various connectors and connector-sdk
|
||||
* [ ] Offer a recommendation or implement a strategy for faasd replication/HA
|
||||
* [ ] Monitor and restart any of the core components at runtime if the container stops
|
||||
* [ ] Asynchronous deletion instead of synchronous
|
||||
* [ ] Asynchronous function deletion instead of synchronous
|
||||
* [ ] Asynchronous function start-up instead of synchronous
|
||||
|
||||
Nice to Have:
|
||||
|
||||
@ -89,6 +89,8 @@ Nice to Have:
|
||||
|
||||
### Completed
|
||||
|
||||
* [x] Docs or examples on how to use the various event connectors (Yes in the eBook)
|
||||
* [x] Resolve core services from functions by populating/sharing `/etc/hosts` between `faasd` and `faasd-provider`
|
||||
* [x] Provide a cloud-init configuration for faasd bootstrap
|
||||
* [x] Configure core services from a docker-compose.yaml file
|
||||
* [x] Store and fetch logs from the journal
|
||||
|
@ -1,8 +1,11 @@
|
||||
package pkg
|
||||
|
||||
const (
|
||||
// FunctionNamespace is the default containerd namespace functions are created
|
||||
FunctionNamespace = "openfaas-fn"
|
||||
// DefaultFunctionNamespace is the default containerd namespace functions are created
|
||||
DefaultFunctionNamespace = "openfaas-fn"
|
||||
|
||||
// NamespaceLabel indicates that a namespace is managed by faasd
|
||||
NamespaceLabel = "openfaas"
|
||||
|
||||
// FaasdNamespace is the containerd namespace services are created
|
||||
FaasdNamespace = "openfaas"
|
||||
|
@ -71,7 +71,7 @@ func buildCmd(ctx context.Context, req logs.Request) *exec.Cmd {
|
||||
|
||||
namespace := req.Namespace
|
||||
if namespace == "" {
|
||||
namespace = faasd.FunctionNamespace
|
||||
namespace = faasd.DefaultFunctionNamespace
|
||||
}
|
||||
|
||||
// find the description of the fields here
|
||||
|
@ -42,6 +42,18 @@ func MakeDeleteHandler(client *containerd.Client, cni gocni.CNI) func(w http.Res
|
||||
|
||||
lookupNamespace := getRequestNamespace(readNamespaceFromQuery(r))
|
||||
|
||||
// Check if namespace exists, and it has the openfaas label
|
||||
valid, err := validNamespace(client, lookupNamespace)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if !valid {
|
||||
http.Error(w, "namespace not valid", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
name := req.FunctionName
|
||||
|
||||
function, err := GetFunction(client, name, lookupNamespace)
|
||||
|
@ -52,10 +52,25 @@ func MakeDeployHandler(client *containerd.Client, cni gocni.CNI, secretMountPath
|
||||
}
|
||||
|
||||
namespace := getRequestNamespace(req.Namespace)
|
||||
|
||||
// Check if namespace exists, and it has the openfaas label
|
||||
valid, err := validNamespace(client, namespace)
|
||||
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if !valid {
|
||||
http.Error(w, "namespace not valid", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
namespaceSecretMountPath := getNamespaceSecretMountPath(secretMountPath, namespace)
|
||||
err = validateSecrets(namespaceSecretMountPath, req.Secrets)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
name := req.Service
|
||||
|
@ -53,7 +53,7 @@ func Test_BuildLabels_WithAnnotations(t *testing.T) {
|
||||
}
|
||||
|
||||
if !reflect.DeepEqual(val, tc.result) {
|
||||
t.Errorf("Got: %s, expected %s", val, tc.result)
|
||||
t.Errorf("Want: %s, got: %s", val, tc.result)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
@ -2,6 +2,7 @@ package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
@ -11,6 +12,7 @@ import (
|
||||
|
||||
"github.com/containerd/containerd"
|
||||
"github.com/containerd/containerd/namespaces"
|
||||
"github.com/openfaas/faasd/pkg"
|
||||
faasd "github.com/openfaas/faasd/pkg"
|
||||
"github.com/openfaas/faasd/pkg/cninetwork"
|
||||
)
|
||||
@ -27,11 +29,23 @@ type Function struct {
|
||||
secrets []string
|
||||
envVars map[string]string
|
||||
envProcess string
|
||||
memoryLimit int64
|
||||
createdAt time.Time
|
||||
}
|
||||
|
||||
// ListFunctions returns a map of all functions with running tasks on namespace
|
||||
func ListFunctions(client *containerd.Client, namespace string) (map[string]*Function, error) {
|
||||
|
||||
// Check if namespace exists, and it has the openfaas label
|
||||
valid, err := validNamespace(client, namespace)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if !valid {
|
||||
return nil, errors.New("namespace not valid")
|
||||
}
|
||||
|
||||
ctx := namespaces.WithNamespace(context.Background(), namespace)
|
||||
functions := make(map[string]*Function)
|
||||
|
||||
@ -79,7 +93,7 @@ func GetFunction(client *containerd.Client, name string, namespace string) (Func
|
||||
|
||||
spec, err := c.Spec(ctx)
|
||||
if err != nil {
|
||||
return Function{}, fmt.Errorf("unable to load function spec for reading secrets: %s, error %w", name, err)
|
||||
return Function{}, fmt.Errorf("unable to load function %s error: %w", name, err)
|
||||
}
|
||||
|
||||
info, err := c.Info(ctx)
|
||||
@ -99,6 +113,7 @@ func GetFunction(client *containerd.Client, name string, namespace string) (Func
|
||||
fn.envVars = envVars
|
||||
fn.envProcess = envProcess
|
||||
fn.createdAt = info.CreatedAt
|
||||
fn.memoryLimit = readMemoryLimitFromSpec(spec)
|
||||
|
||||
replicas := 0
|
||||
task, err := c.Task(ctx, nil)
|
||||
@ -187,7 +202,7 @@ func ListNamespaces(client *containerd.Client) []string {
|
||||
namespaces, err := store.List(context.Background())
|
||||
if err != nil {
|
||||
log.Printf("Error listing namespaces: %s", err.Error())
|
||||
set = append(set, faasd.FunctionNamespace)
|
||||
set = append(set, faasd.DefaultFunctionNamespace)
|
||||
return set
|
||||
}
|
||||
|
||||
@ -198,12 +213,12 @@ func ListNamespaces(client *containerd.Client) []string {
|
||||
continue
|
||||
}
|
||||
|
||||
if _, found := labels["openfaas"]; found {
|
||||
if _, found := labels[pkg.NamespaceLabel]; found {
|
||||
set = append(set, namespace)
|
||||
}
|
||||
|
||||
if !findNamespace(faasd.FunctionNamespace, set) {
|
||||
set = append(set, faasd.FunctionNamespace)
|
||||
if !findNamespace(faasd.DefaultFunctionNamespace, set) {
|
||||
set = append(set, faasd.DefaultFunctionNamespace)
|
||||
}
|
||||
}
|
||||
|
||||
@ -218,3 +233,10 @@ func findNamespace(target string, items []string) bool {
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func readMemoryLimitFromSpec(spec *specs.Spec) int64 {
|
||||
if spec.Linux == nil || spec.Linux.Resources == nil || spec.Linux.Resources.Memory == nil || spec.Linux.Resources.Memory.Limit == nil {
|
||||
return 0
|
||||
}
|
||||
return *spec.Linux.Resources.Memory.Limit
|
||||
}
|
||||
|
@ -32,54 +32,54 @@ func Test_BuildLabelsAndAnnotationsFromServiceSpec_Annotations(t *testing.T) {
|
||||
}
|
||||
|
||||
func Test_SplitMountToSecrets(t *testing.T) {
|
||||
type test struct {
|
||||
Name string
|
||||
Input []specs.Mount
|
||||
Expected []string
|
||||
type testCase struct {
|
||||
Name string
|
||||
Input []specs.Mount
|
||||
Want []string
|
||||
}
|
||||
tests := []test{
|
||||
{Name: "No matching openfaas secrets", Input: []specs.Mount{{Destination: "/foo/"}}, Expected: []string{}},
|
||||
{Name: "Nil mounts", Input: nil, Expected: []string{}},
|
||||
{Name: "No Mounts", Input: []specs.Mount{{Destination: "/foo/"}}, Expected: []string{}},
|
||||
{Name: "One Mounts IS secret", Input: []specs.Mount{{Destination: "/var/openfaas/secrets/secret1"}}, Expected: []string{"secret1"}},
|
||||
{Name: "Multiple Mounts 1 secret", Input: []specs.Mount{{Destination: "/var/openfaas/secrets/secret1"}, {Destination: "/some/other/path"}}, Expected: []string{"secret1"}},
|
||||
{Name: "Multiple Mounts all secrets", Input: []specs.Mount{{Destination: "/var/openfaas/secrets/secret1"}, {Destination: "/var/openfaas/secrets/secret2"}}, Expected: []string{"secret1", "secret2"}},
|
||||
tests := []testCase{
|
||||
{Name: "No matching openfaas secrets", Input: []specs.Mount{{Destination: "/foo/"}}, Want: []string{}},
|
||||
{Name: "Nil mounts", Input: nil, Want: []string{}},
|
||||
{Name: "No Mounts", Input: []specs.Mount{{Destination: "/foo/"}}, Want: []string{}},
|
||||
{Name: "One Mounts IS secret", Input: []specs.Mount{{Destination: "/var/openfaas/secrets/secret1"}}, Want: []string{"secret1"}},
|
||||
{Name: "Multiple Mounts 1 secret", Input: []specs.Mount{{Destination: "/var/openfaas/secrets/secret1"}, {Destination: "/some/other/path"}}, Want: []string{"secret1"}},
|
||||
{Name: "Multiple Mounts all secrets", Input: []specs.Mount{{Destination: "/var/openfaas/secrets/secret1"}, {Destination: "/var/openfaas/secrets/secret2"}}, Want: []string{"secret1", "secret2"}},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.Name, func(t *testing.T) {
|
||||
got := readSecretsFromMounts(tc.Input)
|
||||
if !reflect.DeepEqual(got, tc.Expected) {
|
||||
t.Fatalf("expected %s, got %s", tc.Expected, got)
|
||||
if !reflect.DeepEqual(got, tc.Want) {
|
||||
t.Fatalf("Want %s, got %s", tc.Want, got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func Test_ProcessEnvToEnvVars(t *testing.T) {
|
||||
type test struct {
|
||||
type testCase struct {
|
||||
Name string
|
||||
Input []string
|
||||
Expected map[string]string
|
||||
Want map[string]string
|
||||
fprocess string
|
||||
}
|
||||
tests := []test{
|
||||
{Name: "No matching EnvVars", Input: []string{"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "fprocess=python index.py"}, Expected: make(map[string]string), fprocess: "python index.py"},
|
||||
{Name: "No EnvVars", Input: []string{}, Expected: make(map[string]string), fprocess: ""},
|
||||
{Name: "One EnvVar", Input: []string{"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "fprocess=python index.py", "env=this"}, Expected: map[string]string{"env": "this"}, fprocess: "python index.py"},
|
||||
{Name: "Multiple EnvVars", Input: []string{"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "this=that", "env=var", "fprocess=python index.py"}, Expected: map[string]string{"this": "that", "env": "var"}, fprocess: "python index.py"},
|
||||
{Name: "Nil EnvVars", Input: nil, Expected: make(map[string]string)},
|
||||
tests := []testCase{
|
||||
{Name: "No matching EnvVars", Input: []string{"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "fprocess=python index.py"}, Want: make(map[string]string), fprocess: "python index.py"},
|
||||
{Name: "No EnvVars", Input: []string{}, Want: make(map[string]string), fprocess: ""},
|
||||
{Name: "One EnvVar", Input: []string{"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "fprocess=python index.py", "env=this"}, Want: map[string]string{"env": "this"}, fprocess: "python index.py"},
|
||||
{Name: "Multiple EnvVars", Input: []string{"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "this=that", "env=var", "fprocess=python index.py"}, Want: map[string]string{"this": "that", "env": "var"}, fprocess: "python index.py"},
|
||||
{Name: "Nil EnvVars", Input: nil, Want: make(map[string]string)},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.Name, func(t *testing.T) {
|
||||
got, fprocess := readEnvFromProcessEnv(tc.Input)
|
||||
if !reflect.DeepEqual(got, tc.Expected) {
|
||||
t.Fatalf("expected: %s, got: %s", tc.Expected, got)
|
||||
if !reflect.DeepEqual(got, tc.Want) {
|
||||
t.Fatalf("Want: %s, got: %s", tc.Want, got)
|
||||
}
|
||||
|
||||
if fprocess != tc.fprocess {
|
||||
t.Fatalf("expected fprocess: %s, got: %s", tc.fprocess, got)
|
||||
t.Fatalf("Want fprocess: %s, got: %s", tc.fprocess, got)
|
||||
|
||||
}
|
||||
})
|
||||
@ -87,22 +87,46 @@ func Test_ProcessEnvToEnvVars(t *testing.T) {
|
||||
}
|
||||
|
||||
func Test_findNamespace(t *testing.T) {
|
||||
type test struct {
|
||||
type testCase struct {
|
||||
Name string
|
||||
foundNamespaces []string
|
||||
namespace string
|
||||
Expected bool
|
||||
Want bool
|
||||
}
|
||||
tests := []test{
|
||||
{Name: "Namespace Found", namespace: "fn", foundNamespaces: []string{"fn", "openfaas-fn"}, Expected: true},
|
||||
{Name: "namespace Not Found", namespace: "fn", foundNamespaces: []string{"openfaas-fn"}, Expected: false},
|
||||
tests := []testCase{
|
||||
{Name: "Namespace Found", namespace: "fn", foundNamespaces: []string{"fn", "openfaas-fn"}, Want: true},
|
||||
{Name: "namespace Not Found", namespace: "fn", foundNamespaces: []string{"openfaas-fn"}, Want: false},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.Name, func(t *testing.T) {
|
||||
got := findNamespace(tc.namespace, tc.foundNamespaces)
|
||||
if got != tc.Expected {
|
||||
t.Fatalf("expected %t, got %t", tc.Expected, got)
|
||||
if got != tc.Want {
|
||||
t.Fatalf("Want %t, got %t", tc.Want, got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func Test_readMemoryLimitFromSpec(t *testing.T) {
|
||||
type testCase struct {
|
||||
Name string
|
||||
Spec *specs.Spec
|
||||
Want int64
|
||||
}
|
||||
testLimit := int64(64)
|
||||
tests := []testCase{
|
||||
{Name: "specs.Linux not found", Spec: &specs.Spec{Linux: nil}, Want: int64(0)},
|
||||
{Name: "specs.LinuxResource not found", Spec: &specs.Spec{Linux: &specs.Linux{Resources: nil}}, Want: int64(0)},
|
||||
{Name: "specs.LinuxMemory not found", Spec: &specs.Spec{Linux: &specs.Linux{Resources: &specs.LinuxResources{Memory: nil}}}, Want: int64(0)},
|
||||
{Name: "specs.LinuxMemory.Limit not found", Spec: &specs.Spec{Linux: &specs.Linux{Resources: &specs.LinuxResources{Memory: &specs.LinuxMemory{Limit: nil}}}}, Want: int64(0)},
|
||||
{Name: "Memory limit set as Want", Spec: &specs.Spec{Linux: &specs.Linux{Resources: &specs.LinuxResources{Memory: &specs.LinuxMemory{Limit: &testLimit}}}}, Want: int64(64)},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.Name, func(t *testing.T) {
|
||||
got := readMemoryLimitFromSpec(tc.Spec)
|
||||
if got != tc.Want {
|
||||
t.Fatalf("Want %d, got %d", tc.Want, got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
@ -24,7 +24,7 @@ func (i *InvokeResolver) Resolve(functionName string) (url.URL, error) {
|
||||
actualFunctionName := functionName
|
||||
log.Printf("Resolve: %q\n", actualFunctionName)
|
||||
|
||||
namespace := getNamespace(functionName, faasd.FunctionNamespace)
|
||||
namespace := getNamespace(functionName, faasd.DefaultFunctionNamespace)
|
||||
|
||||
if strings.Contains(functionName, ".") {
|
||||
actualFunctionName = strings.TrimSuffix(functionName, "."+namespace)
|
||||
|
@ -2,6 +2,7 @@ package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"k8s.io/apimachinery/pkg/api/resource"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
@ -14,6 +15,17 @@ func MakeReadHandler(client *containerd.Client) func(w http.ResponseWriter, r *h
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
lookupNamespace := getRequestNamespace(readNamespaceFromQuery(r))
|
||||
// Check if namespace exists, and it has the openfaas label
|
||||
valid, err := validNamespace(client, lookupNamespace)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if !valid {
|
||||
http.Error(w, "namespace not valid", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
res := []types.FunctionStatus{}
|
||||
fns, err := ListFunctions(client, lookupNamespace)
|
||||
@ -26,6 +38,7 @@ func MakeReadHandler(client *containerd.Client) func(w http.ResponseWriter, r *h
|
||||
for _, fn := range fns {
|
||||
annotations := &fn.annotations
|
||||
labels := &fn.labels
|
||||
memory := resource.NewQuantity(fn.memoryLimit, resource.BinarySI)
|
||||
res = append(res, types.FunctionStatus{
|
||||
Name: fn.name,
|
||||
Image: fn.image,
|
||||
@ -36,6 +49,7 @@ func MakeReadHandler(client *containerd.Client) func(w http.ResponseWriter, r *h
|
||||
Secrets: fn.secrets,
|
||||
EnvVars: fn.envVars,
|
||||
EnvProcess: fn.envProcess,
|
||||
Limits: &types.FunctionResources{Memory: memory.String()},
|
||||
CreatedAt: fn.createdAt,
|
||||
})
|
||||
}
|
||||
|
@ -16,6 +16,18 @@ func MakeReplicaReaderHandler(client *containerd.Client) func(w http.ResponseWri
|
||||
functionName := vars["name"]
|
||||
lookupNamespace := getRequestNamespace(readNamespaceFromQuery(r))
|
||||
|
||||
// Check if namespace exists, and it has the openfaas label
|
||||
valid, err := validNamespace(client, lookupNamespace)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if !valid {
|
||||
http.Error(w, "namespace not valid", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if f, err := GetFunction(client, functionName, lookupNamespace); err == nil {
|
||||
found := types.FunctionStatus{
|
||||
Name: functionName,
|
||||
|
@ -41,6 +41,18 @@ func MakeReplicaUpdateHandler(client *containerd.Client, cni gocni.CNI) func(w h
|
||||
|
||||
namespace := getRequestNamespace(readNamespaceFromQuery(r))
|
||||
|
||||
// Check if namespace exists, and it has the openfaas label
|
||||
valid, err := validNamespace(client, namespace)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if !valid {
|
||||
http.Error(w, "namespace not valid", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
name := req.ServiceName
|
||||
|
||||
if _, err := GetFunction(client, name, namespace); err != nil {
|
||||
|
@ -49,6 +49,18 @@ func MakeSecretHandler(c *containerd.Client, mountPath string) func(w http.Respo
|
||||
func listSecrets(c *containerd.Client, w http.ResponseWriter, r *http.Request, mountPath string) {
|
||||
|
||||
lookupNamespace := getRequestNamespace(readNamespaceFromQuery(r))
|
||||
// Check if namespace exists, and it has the openfaas label
|
||||
valid, err := validNamespace(c, lookupNamespace)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if !valid {
|
||||
http.Error(w, "namespace not valid", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
mountPath = getNamespaceSecretMountPath(mountPath, lookupNamespace)
|
||||
|
||||
files, err := ioutil.ReadDir(mountPath)
|
||||
@ -74,6 +86,14 @@ func createSecret(c *containerd.Client, w http.ResponseWriter, r *http.Request,
|
||||
return
|
||||
}
|
||||
|
||||
err = validateSecret(secret)
|
||||
if err != nil {
|
||||
log.Printf("[secret] error %s", err.Error())
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("[secret] is valid: %q", secret.Name)
|
||||
namespace := getRequestNamespace(secret.Namespace)
|
||||
mountPath = getNamespaceSecretMountPath(mountPath, namespace)
|
||||
|
||||
@ -84,7 +104,12 @@ func createSecret(c *containerd.Client, w http.ResponseWriter, r *http.Request,
|
||||
return
|
||||
}
|
||||
|
||||
err = ioutil.WriteFile(path.Join(mountPath, secret.Name), []byte(secret.Value), secretFilePermission)
|
||||
data := secret.RawValue
|
||||
if len(data) == 0 {
|
||||
data = []byte(secret.Value)
|
||||
}
|
||||
|
||||
err = ioutil.WriteFile(path.Join(mountPath, secret.Name), data, secretFilePermission)
|
||||
|
||||
if err != nil {
|
||||
log.Printf("[secret] error %s", err.Error())
|
||||
@ -125,10 +150,6 @@ func parseSecret(r *http.Request) (types.Secret, error) {
|
||||
return secret, err
|
||||
}
|
||||
|
||||
if isTraversal(secret.Name) {
|
||||
return secret, fmt.Errorf(traverseErrorSt)
|
||||
}
|
||||
|
||||
return secret, err
|
||||
}
|
||||
|
||||
@ -138,3 +159,13 @@ func isTraversal(name string) bool {
|
||||
return strings.Contains(name, fmt.Sprintf("%s", string(os.PathSeparator))) ||
|
||||
strings.Contains(name, "..")
|
||||
}
|
||||
|
||||
func validateSecret(secret types.Secret) error {
|
||||
if strings.TrimSpace(secret.Name) == "" {
|
||||
return fmt.Errorf("non-empty name is required")
|
||||
}
|
||||
if isTraversal(secret.Name) {
|
||||
return fmt.Errorf(traverseErrorSt)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
@ -1,63 +1,163 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/openfaas/faas-provider/types"
|
||||
)
|
||||
|
||||
func Test_parseSecretValidName(t *testing.T) {
|
||||
func Test_parseSecret(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
payload string
|
||||
expError string
|
||||
expSecret types.Secret
|
||||
}{
|
||||
{
|
||||
name: "no error when name is valid without extention and with no traversal",
|
||||
payload: `{"name": "authorized_keys", "value": "foo"}`,
|
||||
expSecret: types.Secret{Name: "authorized_keys", Value: "foo"},
|
||||
},
|
||||
{
|
||||
name: "no error when name is valid and parses RawValue correctly",
|
||||
payload: `{"name": "authorized_keys", "rawValue": "YmFy"}`,
|
||||
expSecret: types.Secret{Name: "authorized_keys", RawValue: []byte("bar")},
|
||||
},
|
||||
{
|
||||
name: "no error when name is valid with dot and with no traversal",
|
||||
payload: `{"name": "authorized.keys", "value": "foo"}`,
|
||||
expSecret: types.Secret{Name: "authorized.keys", Value: "foo"},
|
||||
},
|
||||
}
|
||||
|
||||
s := types.Secret{Name: "authorized_keys"}
|
||||
body, _ := json.Marshal(s)
|
||||
reader := bytes.NewReader(body)
|
||||
r := httptest.NewRequest(http.MethodPost, "/", reader)
|
||||
_, err := parseSecret(r)
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
reader := strings.NewReader(tc.payload)
|
||||
r := httptest.NewRequest(http.MethodPost, "/", reader)
|
||||
secret, err := parseSecret(r)
|
||||
if err != nil && tc.expError == "" {
|
||||
t.Fatalf("unexpected error: %s", err)
|
||||
return
|
||||
}
|
||||
|
||||
if tc.expError != "" {
|
||||
if err == nil {
|
||||
t.Fatalf("expected error: %s, got nil", tc.expError)
|
||||
}
|
||||
if err.Error() != tc.expError {
|
||||
t.Fatalf("expected error: %s, got: %s", tc.expError, err)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if !reflect.DeepEqual(secret, tc.expSecret) {
|
||||
t.Fatalf("expected secret: %+v, got: %+v", tc.expSecret, secret)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSecretCreation(t *testing.T) {
|
||||
mountPath, err := os.MkdirTemp("", "test_secret_creation")
|
||||
if err != nil {
|
||||
t.Fatalf("secret name is valid with no traversal characters")
|
||||
}
|
||||
}
|
||||
|
||||
func Test_parseSecretValidNameWithDot(t *testing.T) {
|
||||
|
||||
s := types.Secret{Name: "authorized.keys"}
|
||||
body, _ := json.Marshal(s)
|
||||
reader := bytes.NewReader(body)
|
||||
r := httptest.NewRequest(http.MethodPost, "/", reader)
|
||||
_, err := parseSecret(r)
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("secret name is valid with no traversal characters")
|
||||
}
|
||||
}
|
||||
|
||||
func Test_parseSecretWithTraversalWithSlash(t *testing.T) {
|
||||
|
||||
s := types.Secret{Name: "/root/.ssh/authorized_keys"}
|
||||
body, _ := json.Marshal(s)
|
||||
reader := bytes.NewReader(body)
|
||||
r := httptest.NewRequest(http.MethodPost, "/", reader)
|
||||
_, err := parseSecret(r)
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("secret name should fail due to path traversal")
|
||||
}
|
||||
}
|
||||
|
||||
func Test_parseSecretWithTraversalWithDoubleDot(t *testing.T) {
|
||||
|
||||
s := types.Secret{Name: ".."}
|
||||
body, _ := json.Marshal(s)
|
||||
reader := bytes.NewReader(body)
|
||||
r := httptest.NewRequest(http.MethodPost, "/", reader)
|
||||
_, err := parseSecret(r)
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("secret name should fail due to path traversal")
|
||||
t.Fatalf("unexpected error while creating temp directory: %s", err)
|
||||
}
|
||||
|
||||
defer os.RemoveAll(mountPath)
|
||||
|
||||
handler := MakeSecretHandler(nil, mountPath)
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
verb string
|
||||
payload string
|
||||
status int
|
||||
secretPath string
|
||||
secret string
|
||||
err string
|
||||
}{
|
||||
{
|
||||
name: "returns error when the name contains a traversal",
|
||||
verb: http.MethodPost,
|
||||
payload: `{"name": "/root/.ssh/authorized_keys", "value": "foo"}`,
|
||||
status: http.StatusBadRequest,
|
||||
err: "directory traversal found in name\n",
|
||||
},
|
||||
{
|
||||
name: "returns error when the name contains a traversal",
|
||||
verb: http.MethodPost,
|
||||
payload: `{"name": "..", "value": "foo"}`,
|
||||
status: http.StatusBadRequest,
|
||||
err: "directory traversal found in name\n",
|
||||
},
|
||||
{
|
||||
name: "empty request returns a validation error",
|
||||
verb: http.MethodPost,
|
||||
payload: `{}`,
|
||||
status: http.StatusBadRequest,
|
||||
err: "non-empty name is required\n",
|
||||
},
|
||||
{
|
||||
name: "can create secret from string",
|
||||
verb: http.MethodPost,
|
||||
payload: `{"name": "foo", "value": "bar"}`,
|
||||
status: http.StatusOK,
|
||||
secretPath: "/openfaas-fn/foo",
|
||||
secret: "bar",
|
||||
},
|
||||
{
|
||||
name: "can create secret from raw value",
|
||||
verb: http.MethodPost,
|
||||
payload: `{"name": "foo", "rawValue": "YmFy"}`,
|
||||
status: http.StatusOK,
|
||||
secretPath: "/openfaas-fn/foo",
|
||||
secret: "bar",
|
||||
},
|
||||
{
|
||||
name: "can create secret in non-default namespace from raw value",
|
||||
verb: http.MethodPost,
|
||||
payload: `{"name": "pity", "rawValue": "dGhlIGZvbw==", "namespace": "a-team"}`,
|
||||
status: http.StatusOK,
|
||||
secretPath: "/a-team/pity",
|
||||
secret: "the foo",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
req := httptest.NewRequest(tc.verb, "http://example.com/foo", strings.NewReader(tc.payload))
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler(w, req)
|
||||
|
||||
resp := w.Result()
|
||||
if resp.StatusCode != tc.status {
|
||||
t.Logf("response body: %s", w.Body.String())
|
||||
t.Fatalf("expected status: %d, got: %d", tc.status, resp.StatusCode)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK && w.Body.String() != tc.err {
|
||||
t.Fatalf("expected error message: %q, got %q", tc.err, w.Body.String())
|
||||
|
||||
}
|
||||
|
||||
if tc.secretPath != "" {
|
||||
data, err := os.ReadFile(filepath.Join(mountPath, tc.secretPath))
|
||||
if err != nil {
|
||||
t.Fatalf("can not read the secret from disk: %s", err)
|
||||
}
|
||||
|
||||
if string(data) != tc.secret {
|
||||
t.Fatalf("expected secret value: %s, got %s", tc.secret, string(data))
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
@ -41,6 +41,19 @@ func MakeUpdateHandler(client *containerd.Client, cni gocni.CNI, secretMountPath
|
||||
}
|
||||
name := req.Service
|
||||
namespace := getRequestNamespace(req.Namespace)
|
||||
|
||||
// Check if namespace exists, and it has the openfaas label
|
||||
valid, err := validNamespace(client, namespace)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if !valid {
|
||||
http.Error(w, "namespace not valid", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
namespaceSecretMountPath := getNamespaceSecretMountPath(secretMountPath, namespace)
|
||||
|
||||
function, err := GetFunction(client, name, namespace)
|
||||
|
@ -1,9 +1,13 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"path"
|
||||
|
||||
"github.com/containerd/containerd"
|
||||
|
||||
"github.com/openfaas/faasd/pkg"
|
||||
faasd "github.com/openfaas/faasd/pkg"
|
||||
)
|
||||
|
||||
@ -12,7 +16,7 @@ func getRequestNamespace(namespace string) string {
|
||||
if len(namespace) > 0 {
|
||||
return namespace
|
||||
}
|
||||
return faasd.FunctionNamespace
|
||||
return faasd.DefaultFunctionNamespace
|
||||
}
|
||||
|
||||
func readNamespaceFromQuery(r *http.Request) string {
|
||||
@ -23,3 +27,23 @@ func readNamespaceFromQuery(r *http.Request) string {
|
||||
func getNamespaceSecretMountPath(userSecretPath string, namespace string) string {
|
||||
return path.Join(userSecretPath, namespace)
|
||||
}
|
||||
|
||||
// validNamespace indicates whether the namespace is eligable to be
|
||||
// used for OpenFaaS functions.
|
||||
func validNamespace(client *containerd.Client, namespace string) (bool, error) {
|
||||
if namespace == faasd.DefaultFunctionNamespace {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
store := client.NamespaceService()
|
||||
labels, err := store.Labels(context.Background(), namespace)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
if value, found := labels[pkg.NamespaceLabel]; found && value == "true" {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
@ -15,7 +15,7 @@ func Test_getRequestNamespace(t *testing.T) {
|
||||
requestNamespace string
|
||||
expectedNamespace string
|
||||
}{
|
||||
{name: "RequestNamespace is not provided", requestNamespace: "", expectedNamespace: faasd.FunctionNamespace},
|
||||
{name: "RequestNamespace is not provided", requestNamespace: "", expectedNamespace: faasd.DefaultFunctionNamespace},
|
||||
{name: "RequestNamespace is provided", requestNamespace: "user-namespace", expectedNamespace: "user-namespace"},
|
||||
}
|
||||
|
||||
@ -23,7 +23,7 @@ func Test_getRequestNamespace(t *testing.T) {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
actualNamespace := getRequestNamespace(tc.requestNamespace)
|
||||
if actualNamespace != tc.expectedNamespace {
|
||||
t.Errorf("Got: %s, expected %s", actualNamespace, tc.expectedNamespace)
|
||||
t.Errorf("Want: %s, got: %s", actualNamespace, tc.expectedNamespace)
|
||||
}
|
||||
})
|
||||
}
|
||||
@ -36,7 +36,7 @@ func Test_getNamespaceSecretMountPath(t *testing.T) {
|
||||
requestNamespace string
|
||||
expectedSecretPath string
|
||||
}{
|
||||
{name: "Default Namespace is provided", requestNamespace: faasd.FunctionNamespace, expectedSecretPath: "/var/openfaas/secrets/" + faasd.FunctionNamespace},
|
||||
{name: "Default Namespace is provided", requestNamespace: faasd.DefaultFunctionNamespace, expectedSecretPath: "/var/openfaas/secrets/" + faasd.DefaultFunctionNamespace},
|
||||
{name: "User Namespace is provided", requestNamespace: "user-namespace", expectedSecretPath: "/var/openfaas/secrets/user-namespace"},
|
||||
}
|
||||
|
||||
@ -44,7 +44,7 @@ func Test_getNamespaceSecretMountPath(t *testing.T) {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
actualNamespace := getNamespaceSecretMountPath(userSecretPath, tc.requestNamespace)
|
||||
if actualNamespace != tc.expectedSecretPath {
|
||||
t.Errorf("Got: %s, expected %s", actualNamespace, tc.expectedSecretPath)
|
||||
t.Errorf("Want: %s, got: %s", actualNamespace, tc.expectedSecretPath)
|
||||
}
|
||||
})
|
||||
}
|
||||
@ -68,7 +68,7 @@ func Test_readNamespaceFromQuery(t *testing.T) {
|
||||
|
||||
actualNamespace := readNamespaceFromQuery(r)
|
||||
if actualNamespace != tc.expectedNamespace {
|
||||
t.Errorf("Got: %s, expected %s", actualNamespace, tc.expectedNamespace)
|
||||
t.Errorf("Want: %s, got: %s", actualNamespace, tc.expectedNamespace)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
Reference in New Issue
Block a user