@@ -2,6 +2,7 @@ package function
22
33import (
44 "bytes"
5+ "context"
56 "encoding/hex"
67 "encoding/json"
78 "fmt"
@@ -15,6 +16,8 @@ import (
1516 "time"
1617
1718 "github.com/alexellis/hmac"
19+ faasSDK "github.com/openfaas/faas-cli/proxy"
20+ "github.com/openfaas/faas-cli/stack"
1821 "github.com/openfaas/openfaas-cloud/sdk"
1922)
2023
@@ -32,17 +35,26 @@ var (
3235 imageValidator = regexp .MustCompile ("(?:[a-zA-Z0-9./]*(?:[._-][a-z0-9]?)*(?::[0-9]+)?[a-zA-Z0-9./]+(?:[._-][a-z0-9]+)*/)*[a-zA-Z0-9]+(?:[._-][a-z0-9]+)+(?::[a-zA-Z0-9._-]+)?" )
3336)
3437
35- type FunctionResources struct {
36- Memory string `json:"memory,omitempty"`
37- CPU string `json:"cpu,omitempty"`
38- }
39-
4038type CPULimits struct {
4139 Limit string
4240 Requests string
4341 Available bool
4442}
4543
44+ //FaaSAuth Authentication type for OpenFaaS
45+ type FaaSAuth struct {
46+ }
47+
48+ //Set add basic authentication to the request
49+ func (auth * FaaSAuth ) Set (req * http.Request ) error {
50+ return sdk .AddBasicAuth (req )
51+ }
52+
53+ var (
54+ timeout = 3 * time .Second
55+ namespace = ""
56+ )
57+
4658// Handle submits the tar to the of-builder then configures an OpenFaaS
4759// deployment based upon stack.yml found in the Git repo. Finally starts
4860// a rolling deployment of the function.
@@ -174,6 +186,9 @@ func Handle(req []byte) string {
174186 log .Fatal (msg )
175187 return msg
176188 }
189+ // Initializing the client and context
190+ client := faasSDK .NewClient (& FaaSAuth {}, gatewayURL , nil , & timeout )
191+ ctx := context .Background ()
177192
178193 if len (imageName ) > 0 {
179194 // Replace image name for "localhost" for deployment
@@ -218,10 +233,10 @@ func Handle(req []byte) string {
218233 userAnnotations := buildAnnotations (annotationWhitelist , event .Annotations )
219234 userAnnotations [sdk .FunctionLabelPrefix + "git-repo-url" ] = event .RepoURL
220235
221- deploy := deployment {
222- Service : serviceValue ,
223- Image : imageName ,
224- Network : "func_functions" ,
236+ deploy := & faasSDK. DeployFunctionSpec {
237+ FunctionName : serviceValue ,
238+ Image : imageName ,
239+ Network : "func_functions" ,
225240 Labels : map [string ]string {
226241 "faas_function" : serviceValue ,
227242 "app" : serviceValue ,
@@ -240,25 +255,27 @@ func Handle(req []byte) string {
240255 sdk .FunctionLabelPrefix + "git-scm" : event .SCM ,
241256 sdk .FunctionLabelPrefix + "git-branch" : buildBranch (),
242257 },
243- Annotations : userAnnotations ,
244- Requests : & FunctionResources {},
245- Limits : & FunctionResources {},
258+ Annotations : userAnnotations ,
259+ FunctionResourceRequest : faasSDK.FunctionResourceRequest {
260+ Limits : & stack.FunctionResources {},
261+ Requests : & stack.FunctionResources {},
262+ },
246263 EnvVars : event .Environment ,
247264 Secrets : event .Secrets ,
248265 ReadOnlyRootFilesystem : readOnlyRootFS ,
249266 }
250267
251- deploy .Limits .Memory = defaultMemoryLimit
268+ deploy .FunctionResourceRequest . Limits .Memory = defaultMemoryLimit
252269
253270 cpuLimit := getCPULimit ()
254271 if cpuLimit .Available {
255272
256273 if len (cpuLimit .Limit ) > 0 {
257- deploy .Limits .CPU = cpuLimit .Limit
274+ deploy .FunctionResourceRequest . Limits .CPU = cpuLimit .Limit
258275 }
259276
260277 if len (cpuLimit .Requests ) > 0 {
261- deploy .Requests .CPU = cpuLimit .Requests
278+ deploy .FunctionResourceRequest . Requests .CPU = cpuLimit .Requests
262279 }
263280 }
264281
@@ -268,8 +285,7 @@ func Handle(req []byte) string {
268285 deploy .RegistryAuth = registryAuth
269286 }
270287
271- deployResult , err := deployFunction (deploy , gatewayURL )
272-
288+ deployResult , err := deployFunction (ctx , client , deploy , gatewayURL )
273289 log .Println (deployResult )
274290
275291 if err != nil {
@@ -470,82 +486,40 @@ func getEventFromEnv() (*sdk.Event, error) {
470486 return & info , err
471487}
472488
473- func functionExists (deploy deployment , gatewayURL string ) (bool , error ) {
474-
475- r , _ := http .NewRequest (http .MethodGet , gatewayURL + "system/functions" , nil )
476-
477- addAuthErr := sdk .AddBasicAuth (r )
478- if addAuthErr != nil {
479- log .Printf ("Basic auth error %s" , addAuthErr )
480- }
481-
482- res , err := http .DefaultClient .Do (r )
483-
489+ func functionExists (ctx context.Context , client * faasSDK.Client , functionName string , gatewayURL string ) (bool , error ) {
490+ // client := faasSDK.NewClient(&FaaSAuth{}, gatewayURL, nil, &timeout)
491+ functions , err := client .ListFunctions (ctx , namespace )
484492 if err != nil {
485- fmt .Println (err )
486493 return false , err
487494 }
488495
489- defer res .Body .Close ()
490-
491- fmt .Println ("functionExists status: " + res .Status )
492- result , _ := ioutil .ReadAll (res .Body )
493-
494- functions := []function {}
495- json .Unmarshal (result , & functions )
496-
497496 for _ , function1 := range functions {
498- if function1 .Name == deploy . Service {
497+ if function1 .Name == functionName {
499498 return true , nil
500499 }
501500 }
502501
503502 return false , err
504503}
505504
506- func deployFunction (deploy deployment , gatewayURL string ) (string , error ) {
507- exists , err := functionExists (deploy , gatewayURL )
505+ func deployFunction (ctx context.Context , client * faasSDK.Client , deploySpec * faasSDK.DeployFunctionSpec , gatewayURL string ) (string , error ) {
506+ var (
507+ err error
508+ )
509+ exists , err := functionExists (ctx , client , deploySpec .FunctionName , gatewayURL )
508510
509- bytesOut , _ := json .Marshal (deploy )
510-
511- reader := bytes .NewBuffer (bytesOut )
512-
513- fmt .Println ("Deploying: " + deploy .Image + " as " + deploy .Service )
514- var res * http.Response
515- var httpReq * http.Request
516- var method string
511+ fmt .Println ("Deploying: " + deploySpec .Image + " as " + deploySpec .FunctionName )
512+ // client := faasSDK.NewClient(&FaaSAuth{}, gatewayURL, nil, &timeout)
517513 if exists {
518- method = http .MethodPut
519- } else {
520- method = http .MethodPost
514+ deploySpec .Update = true
521515 }
522516
523- httpReq , err = http .NewRequest (method , gatewayURL + "system/functions" , reader )
524- httpReq .Header .Set ("Content-Type" , "application/json" )
525-
526- addAuthErr := sdk .AddBasicAuth (httpReq )
527- if addAuthErr != nil {
528- log .Printf ("Basic auth error %s" , addAuthErr )
517+ resStatus := client .DeployFunction (ctx , deploySpec )
518+ log .Printf ("Deploy status - %d" , resStatus )
519+ if resStatus < 200 || resStatus > 299 {
520+ return "" , fmt .Errorf ("http status code %d" , resStatus )
529521 }
530-
531- res , err = http .DefaultClient .Do (httpReq )
532-
533- if err != nil {
534- log .Printf ("error %s to system/functions %s" , method , err )
535- return "" , err
536- }
537-
538- defer res .Body .Close ()
539-
540- log .Printf ("Deploy status [%s] - %d" , method , res .StatusCode )
541-
542- buildStatus , _ := ioutil .ReadAll (res .Body )
543-
544- if res .StatusCode < 200 || res .StatusCode > 299 {
545- return "" , fmt .Errorf ("http status code %d, error: %s" , res .StatusCode , string (buildStatus ))
546- }
547-
548- return string (buildStatus ), err
522+ return fmt .Sprintf ("%s deployed successfully" , deploySpec .FunctionName ), err
549523}
550524
551525func enableStatusReporting () bool {
@@ -602,29 +576,6 @@ func validImage(image string) bool {
602576 return false
603577}
604578
605- type deployment struct {
606- Service string
607- Image string
608- Network string
609- Labels map [string ]string `json:"labels"`
610- Limits * FunctionResources `json:"limits,omitempty"`
611- Requests * FunctionResources `json:"requests,omitempty"`
612- EnvVars map [string ]string `json:"envVars"` // EnvVars provides overrides for functions.
613- Secrets []string `json:"secrets"`
614- ReadOnlyRootFilesystem bool `json:"readOnlyRootFilesystem"`
615- RegistryAuth string `json:"registryAuth"`
616- Annotations map [string ]string `json:"annotations"`
617- }
618-
619- type Limits struct {
620- Memory string
621- CPU string
622- }
623-
624- type function struct {
625- Name string
626- }
627-
628579func getRegistryAuthSecret () string {
629580 path := "/var/openfaas/secrets/swarm-pull-secret"
630581 if _ , err := os .Stat (path ); err == nil {
0 commit comments