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) Lua Scripting for Dynamic Kubernetes Deployments #960

Merged
merged 1 commit into from
Jan 20, 2025
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
5 changes: 3 additions & 2 deletions api/v1alpha1/zz_generated.deepcopy.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions api/v1beta1/zz_generated.deepcopy.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ var (
healthAddr string
profilerAddress string
driftDetectionConfigMap string
luaConfigMap string
disableCaching bool
disableTelemetry bool
)
Expand Down Expand Up @@ -169,6 +170,7 @@ func main() {
ctx := ctrl.SetupSignalHandler()
controllers.SetManagementClusterAccess(mgr.GetClient(), mgr.GetConfig())
controllers.SetDriftdetectionConfigMap(driftDetectionConfigMap)
controllers.SetLuaConfigMap(luaConfigMap)

logsettings.RegisterForLogSettings(ctx,
libsveltosv1beta1.ComponentAddonManager, ctrl.Log.WithName("log-setter"),
Expand Down Expand Up @@ -239,6 +241,10 @@ func initFlags(fs *pflag.FlagSet) {
fs.StringVar(&driftDetectionConfigMap, "drift-detection-config", "",
"The name of the ConfigMap in the projectsveltos namespace containing the drift-detection-manager configuration")

fs.StringVar(&luaConfigMap, "lua-methods", "",
"The name of the ConfigMap in the projectsveltos namespace containing lua utilities to be loaded."+
"Changing the content of the ConfigMap does not cause Sveltos to redeploy.")

const defautlRestConfigQPS = 20
fs.Float32Var(&restConfigQPS, "kube-api-qps", defautlRestConfigQPS,
fmt.Sprintf("Maximum queries per second from the controller client to the Kubernetes API server. Defaults to %d",
Expand Down
30 changes: 27 additions & 3 deletions controllers/handlers_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,19 @@ func instantiateTemplate(referencedObject client.Object, logger logr.Logger) boo
return false
}

func instantiateWithLua(referencedObject client.Object, logger logr.Logger) bool {
annotations := referencedObject.GetAnnotations()
if annotations != nil {
if _, ok := annotations[libsveltosv1beta1.PolicyLuaAnnotation]; ok {
logger.V(logs.LogInfo).Info(fmt.Sprintf("referencedObject %s %s/%s contains a lua script",
referencedObject.GetObjectKind().GroupVersionKind().Kind, referencedObject.GetNamespace(), referencedObject.GetName()))
return true
}
}

return false
}

func getSubresources(referencedObject client.Object) []string {
annotations := referencedObject.GetAnnotations()
if annotations != nil {
Expand All @@ -354,7 +367,8 @@ func deployContent(ctx context.Context, deployingToMgmtCluster bool, destConfig

subresources := getSubresources(referencedObject)
instantiateTemplate := instantiateTemplate(referencedObject, logger)
resources, err := collectContent(ctx, clusterSummary, mgmtResources, data, instantiateTemplate, logger)
instantiateLua := instantiateWithLua(referencedObject, logger)
resources, err := collectContent(ctx, clusterSummary, mgmtResources, data, instantiateTemplate, instantiateLua, logger)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -941,7 +955,7 @@ func customSplit(text string) ([]string, error) {
// Returns an error if one occurred. Otherwise it returns a slice of *unstructured.Unstructured.
func collectContent(ctx context.Context, clusterSummary *configv1beta1.ClusterSummary,
mgmtResources map[string]*unstructured.Unstructured, data map[string]string,
instantiateTemplate bool, logger logr.Logger,
instantiateTemplate, instantiateLua bool, logger logr.Logger,
) ([]*unstructured.Unstructured, error) {

policies := make([]*unstructured.Unstructured, 0, len(data))
Expand All @@ -958,6 +972,16 @@ func collectContent(ctx context.Context, clusterSummary *configv1beta1.ClusterSu
return nil, err
}

section = instance
} else if instantiateLua {
instance, err := instantiateWithLuaScript(ctx, getManagementClusterConfig(), getManagementClusterClient(),
clusterSummary.Spec.ClusterType, clusterSummary.Spec.ClusterNamespace, clusterSummary.Spec.ClusterName,
section, mgmtResources, logger)
if err != nil {
logger.Error(err, fmt.Sprintf("failed to instantiate policy from Data %.100s", section))
return nil, err
}
logger.V(logs.LogInfo).Info(fmt.Sprintf("lua output %q", instance))
section = instance
}

Expand Down Expand Up @@ -1993,7 +2017,7 @@ func getClusterProfileSpecHash(ctx context.Context, clusterSummary *configv1beta
// If drift-detectionmanager configuration is in a ConfigMap. fetch ConfigMap and use its Data
// section in the hash evaluation.
if driftDetectionConfigMap := getDriftDetectionConfigMap(); driftDetectionConfigMap != "" {
configMap, err := collectDriftDetectionConfigMap(ctx, driftDetectionConfigMap)
configMap, err := collectDriftDetectionConfigMap(ctx)
if err != nil {
return nil, err
}
Expand Down
4 changes: 2 additions & 2 deletions controllers/handlers_utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1419,7 +1419,7 @@ subjects:
`
data := map[string]string{"policy.yaml": content}
u, err := controllers.CollectContent(context.TODO(), clusterSummary, nil, data, false,
textlogger.NewLogger(textlogger.NewConfig()))
false, textlogger.NewLogger(textlogger.NewConfig()))
Expect(err).To(BeNil())
Expect(len(u)).To(Equal(1))
Expect(u[0].GetName()).To(Equal("contour-gateway-provisioner"))
Expand Down Expand Up @@ -1480,7 +1480,7 @@ stringData:
policies := []string{service, deployment, secret}
configMap := createConfigMapWithPolicy(randomString(), randomString(), policies...)
u, err := controllers.CollectContent(context.TODO(), clusterSummary, nil, configMap.Data, false,
textlogger.NewLogger(textlogger.NewConfig()))
false, textlogger.NewLogger(textlogger.NewConfig()))
Expect(err).To(BeNil())
Expect(len(u)).To(Equal(3))
})
Expand Down
126 changes: 126 additions & 0 deletions controllers/lua_instantiation.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
/*
Copyright 2024. projectsveltos.io. All rights reserved.
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.
*/

package controllers

import (
"context"
"encoding/json"
"fmt"

"github.com/go-logr/logr"
lua "github.com/yuin/gopher-lua"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/client-go/rest"
"sigs.k8s.io/controller-runtime/pkg/client"

libsveltosv1beta1 "github.com/projectsveltos/libsveltos/api/v1beta1"
logs "github.com/projectsveltos/libsveltos/lib/logsettings"
sveltoslua "github.com/projectsveltos/libsveltos/lib/lua"
)

type luaResult struct {
// Resources is a list of Kubernetes resources
Resources string `json:"resources"`
}

func instantiateWithLuaScript(ctx context.Context, config *rest.Config, c client.Client,
clusterType libsveltosv1beta1.ClusterType, clusterNamespace, clusterName, script string,
mgmtResources map[string]*unstructured.Unstructured, logger logr.Logger) (string, error) {

if script == "" {
return "", nil
}

luaCode := ""

if luaConfigMap := getLuaConfigMap(); luaConfigMap != "" {
configMap, err := collectLuaConfigMap(ctx)
if err != nil {
return "", err
}

for k := range configMap.Data {
luaCode += configMap.Data[k]
luaCode += "\n"
}
}

luaCode += script

objects, err := fecthClusterObjects(ctx, config, c, clusterNamespace, clusterName, clusterType, logger)
if err != nil {
return "", err
}

if mgmtResources != nil {
objects.MgmtResources = make(map[string]map[string]interface{})
for k := range mgmtResources {
logger.V(logs.LogDebug).Info(fmt.Sprintf("using mgmt resource %s %s/%s with identifier %s",
mgmtResources[k].GetKind(), mgmtResources[k].GetNamespace(), mgmtResources[k].GetName(), k))
objects.MgmtResources[k] = mgmtResources[k].UnstructuredContent()
}
}

// Create a new Lua state
l := lua.NewState()
defer l.Close()

sveltoslua.LoadModulesAndRegisterMethods(l)

// Load the Lua code
if err := l.DoString(luaCode); err != nil {
logger.V(logs.LogInfo).Info(fmt.Sprintf("doString failed: %v", err))
return "", err
}

argTable := l.NewTable()
for key, resource := range objects.MgmtResources {
lValue := sveltoslua.MapToTable(resource)
argTable.RawSetString(key, lValue)
}

l.SetGlobal("resources", argTable)

if err := l.CallByParam(lua.P{
Fn: l.GetGlobal("evaluate"), // name of Lua function
NRet: 1, // number of returned values
Protect: true, // return err or panic
}, argTable); err != nil {
logger.V(logs.LogInfo).Info(fmt.Sprintf("failed to call evaluate function: %s", err.Error()))
return "", err
}

lv := l.Get(-1)
tbl, ok := lv.(*lua.LTable)
if !ok {
logger.V(logs.LogInfo).Info(sveltoslua.LuaTableError)
return "", fmt.Errorf("%s", sveltoslua.LuaTableError)
}

goResult := sveltoslua.ToGoValue(tbl)
resultJson, err := json.Marshal(goResult)
if err != nil {
logger.V(logs.LogInfo).Info(fmt.Sprintf("failed to marshal result: %v", err))
return "", err
}

var result luaResult
err = json.Unmarshal(resultJson, &result)
if err != nil {
logger.V(logs.LogInfo).Info(fmt.Sprintf("failed to marshal result: %v", err))
return "", err
}

return result.Resources, nil
}
Loading
Loading