Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: provide an option to deploy private services #132

Merged
merged 3 commits into from
Oct 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/cli/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ func (c *icli) init(cCtx *cli.Context) error {
projectDirectory,
cCtx.String(runtimeVersionFlag),
version,
cCtx.Bool(isPrivateServiceFlag),
imagePullSecrets,
c.Resources,
)
Expand Down
59 changes: 49 additions & 10 deletions src/cli/deploy.go
Original file line number Diff line number Diff line change
@@ -1,40 +1,79 @@
package cli

import (
"fmt"

"github.com/nearform/initium-cli/src/services/git"
knative "github.com/nearform/initium-cli/src/services/k8s"
"github.com/urfave/cli/v2"
)

func (c *icli) Deploy(cCtx *cli.Context) error {
config, err := knative.Config(
cCtx.String(endpointFlag),
cCtx.String(tokenFlag),
[]byte(cCtx.String(caCRTFlag)),
)
namespace := cCtx.String(namespaceFlag)
envFile := cCtx.String(envVarFileFlag)

project, err := c.getProject(cCtx)
if err != nil {
return err
}
project, err := c.getProject(cCtx)

commitSha, err := git.GetHash()
if err != nil {
return err
}

commitSha, err := git.GetHash()
serviceManifest, err := knative.LoadManifest(namespace, commitSha, project, c.dockerImage, envFile)
if err != nil {
return err
}

return knative.Apply(cCtx.String(namespaceFlag), commitSha, config, project, c.dockerImage, cCtx.String(envVarFileFlag))
if cCtx.Bool(dryRunFlag) {
yamlBytes, err := knative.ToYaml(serviceManifest)
if err != nil {
return err
}
fmt.Fprintf(c.Writer, "%s", yamlBytes)
return nil
}

config, err := knative.Config(
cCtx.String(endpointFlag),
cCtx.String(tokenFlag),
[]byte(cCtx.String(caCRTFlag)),
)

if err != nil {
return err
}

return knative.Apply(serviceManifest, config)
}

func (c icli) DeployCMD() *cli.Command {
flags := c.CommandFlags([]FlagsType{Kubernetes, Shared})

flags = append(flags, &cli.BoolFlag{
Name: dryRunFlag,
Usage: "print out the knative manifest without applying it",
Value: false,
})

return &cli.Command{
Name: "deploy",
Usage: "deploy the application as a knative service",
Flags: c.CommandFlags([]FlagsType{Kubernetes, Shared}),
Flags: flags,
Action: c.Deploy,
Before: c.baseBeforeFunc,
Before: func(ctx *cli.Context) error {
if err := c.loadFlagsFromConfig(ctx); err != nil {
return err
}

ignoredFlags := []string{}
if ctx.Bool(dryRunFlag) {
ignoredFlags = append(ignoredFlags, endpointFlag, tokenFlag, caCRTFlag)
}

return c.checkRequiredFlags(ctx, ignoredFlags)
},
}
}
21 changes: 19 additions & 2 deletions src/cli/flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"io/ioutil"
"os"
"strconv"
"strings"

"github.com/nearform/initium-cli/src/services/git"
Expand Down Expand Up @@ -46,6 +47,8 @@ const (
stopOnBuildFlag string = "stop-on-build"
stopOnPushFlag string = "stop-on-push"
envVarFileFlag string = "env-var-file"
isPrivateServiceFlag string = "private"
dryRunFlag string = "dry-run"
)

type flags struct {
Expand Down Expand Up @@ -109,6 +112,12 @@ func InitFlags() flags {
Required: false,
Category: "deploy",
},
&cli.BoolFlag{
Name: isPrivateServiceFlag,
Usage: "Do not expose the service public endpoint",
Category: "init",
Value: false,
},
&cli.StringFlag{
Name: envVarFileFlag,
Value: defaults.EnvVarFile,
Expand Down Expand Up @@ -250,9 +259,17 @@ func (c icli) loadFlagsFromConfig(ctx *cli.Context) error {
for _, name := range v.Names() {
c.Logger.Debugf("%s is set = %v", name, ctx.IsSet(name))
if name != "help" && !slices.Contains(excludedFlags, name) && config[name] != nil && !ctx.IsSet(mainName) {
if err := ctx.Set(mainName, config[name].(string)); err != nil {
return err
switch config[name].(type) {
case bool:
if err := ctx.Set(mainName, strconv.FormatBool(config[name].(bool))); err != nil {
return err
}
default:
if err := ctx.Set(mainName, config[name].(string)); err != nil {
return err
}
}

}
}
}
Expand Down
8 changes: 8 additions & 0 deletions src/cli/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"os"
"path/filepath"
"sort"
"strconv"
"strings"

"github.com/charmbracelet/log"
Expand Down Expand Up @@ -86,6 +87,13 @@ func (c icli) InitConfigCMD(ctx *cli.Context) error {
}
n = stringSliceFlag.Name
v = strings.Join(ctx.StringSlice(stringSliceFlag.Name), ",")
case *cli.BoolFlag:
boolFlag := flag.(*cli.BoolFlag)
if slices.Contains(excludedFlags, boolFlag.Name) {
continue
}
n = boolFlag.Name
v = strconv.FormatBool(ctx.Bool(boolFlag.Name))
}

if v == "" {
Expand Down
14 changes: 8 additions & 6 deletions src/cli/init_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,19 @@ import (
"github.com/charmbracelet/log"
)

func compareConfig(t *testing.T, appName string, registry string, writer io.Writer) {
func compareConfig(t *testing.T, appName string, registry string, isPrivateService bool, writer io.Writer) {
configTemplate := fmt.Sprintf(`app-name: %s
container-registry: %s
default-branch: main
dockerfile-name: null
env-var-file: .env.initium
image-pull-secrets: null
private: %t
runtime-version: null
`,
appName,
registry,
isPrivateService,
)

result := fmt.Sprint(writer.(*bytes.Buffer))
Expand Down Expand Up @@ -80,7 +82,7 @@ func TestInitConfig(t *testing.T) {
if err = icli.Run([]string{"initium", fmt.Sprintf("--config-file=%s", f.Name()), "init", "config"}); err != nil {
t.Error(err)
}
compareConfig(t, "FromFile", registry, icli.Writer)
compareConfig(t, "FromFile", registry, false, icli.Writer)

// Environment Variable wins over config
os.Setenv("INITIUM_APP_NAME", "FromEnv")
Expand All @@ -89,14 +91,14 @@ func TestInitConfig(t *testing.T) {
if err = icli.Run([]string{"initium", fmt.Sprintf("--config-file=%s", f.Name()), "init", "config"}); err != nil {
t.Error(err)
}
compareConfig(t, "FromEnv", registry, icli.Writer)
compareConfig(t, "FromEnv", registry, false, icli.Writer)

// Command line argument wins over config and Environment variable
reseticliBuffer(&icli)
if err = icli.Run([]string{"initium", fmt.Sprintf("--config-file=%s", f.Name()), "init", "config", "--app-name=FromParam"}); err != nil {
t.Error(err)
}
compareConfig(t, "FromParam", registry, icli.Writer)
compareConfig(t, "FromParam", registry, false, icli.Writer)

}

Expand All @@ -119,14 +121,14 @@ func TestRepoNameRetrocompatibiliy(t *testing.T) {
if err = cli.Run([]string{"initium", fmt.Sprintf("--config-file=%s", f.Name()), "init", "config", "--app-name=FromParam"}); err != nil {
t.Error(err)
}
compareConfig(t, "FromParam", "FromFile", cli.Writer)
compareConfig(t, "FromParam", "FromFile", false, cli.Writer)

//Override from parameter
reseticliBuffer(&cli)
if err = cli.Run([]string{"initium", fmt.Sprintf("--config-file=%s", f.Name()), "init", "config", "--app-name=FromParam", "--container-registry=ghcr.io/nearform"}); err != nil {
t.Error(err)
}
compareConfig(t, "FromParam", "ghcr.io/nearform", cli.Writer)
compareConfig(t, "FromParam", "ghcr.io/nearform", false, cli.Writer)
}

func TestAppName(t *testing.T) {
Expand Down
56 changes: 42 additions & 14 deletions src/services/k8s/knative.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,13 @@ import (
"github.com/nearform/initium-cli/src/services/docker"
"github.com/nearform/initium-cli/src/services/project"
"github.com/nearform/initium-cli/src/utils/defaults"
"sigs.k8s.io/yaml"

corev1 "k8s.io/api/core/v1"
apimachineryErrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/serializer"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/rest"
Expand All @@ -30,6 +33,8 @@ import (
const (
UpdateShaAnnotationName = "initium.nearform.com/updateSha"
UpdateTimestampAnnotationName = "initium.nearform.com/updateTimestamp"
visibilityLabel = "networking.knative.dev/visibility"
visibilityLabelPrivateValue = "cluster-local"
)

func Config(endpoint string, token string, caCrt []byte) (*rest.Config, error) {
Expand All @@ -46,16 +51,25 @@ func Config(endpoint string, token string, caCrt []byte) (*rest.Config, error) {
}, nil
}

func loadManifest(namespace string, commitSha string, project *project.Project, dockerImage docker.DockerImage, envFile string) (*servingv1.Service, error) {
func setLabels(manifest *servingv1.Service, project project.Project) {
if manifest.ObjectMeta.Labels == nil {
manifest.ObjectMeta.Labels = map[string]string{}
}
if project.IsPrivate {
manifest.ObjectMeta.Labels[visibilityLabel] = visibilityLabelPrivateValue
}
}

func LoadManifest(namespace string, commitSha string, project *project.Project, dockerImage docker.DockerImage, envFile string) (*servingv1.Service, error) {
knativeTemplate := path.Join("assets", "knative", "service.yaml.tmpl")
template, err := template.ParseFS(project.Resources, knativeTemplate)
if err != nil {
return nil, fmt.Errorf("error reading the knative service yaml: %v", err)
}

templateParams := map[string]interface{}{
"Name": dockerImage.Name,
"RemoteTag": dockerImage.RemoteTag(),
"Name": dockerImage.Name,
"RemoteTag": dockerImage.RemoteTag(),
"ImagePullSecrets": project.ImagePullSecrets,
}

Expand Down Expand Up @@ -90,16 +104,24 @@ func loadManifest(namespace string, commitSha string, project *project.Project,
UpdateTimestampAnnotationName: time.Now().Format(time.RFC3339),
}

envVarList, err := loadEnvFile(envFile)
if err != nil {
setLabels(service, *project)
if err = setEnv(service, envFile); err != nil {
return nil, err
}

service.Spec.Template.Spec.Containers[0].Env = append(service.Spec.Template.Spec.Containers[0].Env, envVarList...)

return service, nil
}

func setEnv(manifest *servingv1.Service, envFile string) error {
envVarList, err := loadEnvFile(envFile)
if err != nil {
return err
}

manifest.Spec.Template.Spec.Containers[0].Env = append(manifest.Spec.Template.Spec.Containers[0].Env, envVarList...)
return nil
}

func loadEnvFile(envFile string) ([]corev1.EnvVar, error) {
var envVarList []corev1.EnvVar
if _, err := os.Stat(envFile); err != nil {
Expand Down Expand Up @@ -156,15 +178,21 @@ func loadEnvFile(envFile string) ([]corev1.EnvVar, error) {
return envVarList, nil
}

func Apply(namespace string, commitSha string, config *rest.Config, project *project.Project, dockerImage docker.DockerImage, envFile string) error {
log.Info("Deploying Knative service", "host", config.Host, "name", project.Name, "namespace", namespace)
ctx, cancel := context.WithTimeout(context.Background(), time.Minute*5)
defer cancel()

serviceManifest, err := loadManifest(namespace, commitSha, project, dockerImage, envFile)
func ToYaml(serviceManifest *servingv1.Service) ([]byte, error) {
scheme := runtime.NewScheme()
servingv1.AddToScheme(scheme)
codec := serializer.NewCodecFactory(scheme).LegacyCodec(servingv1.SchemeGroupVersion)
jsonBytes, err := runtime.Encode(codec, serviceManifest)
if err != nil {
return err
return nil, err
}
return yaml.JSONToYAML(jsonBytes)
}

func Apply(serviceManifest *servingv1.Service, config *rest.Config) error {
log.Info("Deploying Knative service", "host", config.Host, "name", serviceManifest.ObjectMeta.Name, "namespace", serviceManifest.ObjectMeta.Namespace)
ctx, cancel := context.WithTimeout(context.Background(), time.Minute*5)
defer cancel()

// Create a new Knative Serving client
servingClient, err := servingv1client.NewForConfig(config)
Expand Down
Loading