From 8c912b2b22af8fe35d4a0963dc98e9b9341df666 Mon Sep 17 00:00:00 2001 From: barnettZQG Date: Fri, 11 Sep 2020 21:21:19 +0800 Subject: [PATCH] support set maven user setting config --- api/api/api_interface.go | 5 + api/api_routers/version2/v2Routers.go | 5 + api/controller/cluster.go | 59 ++++++++ api/handler/cluster.go | 131 ++++++++++++++++- api/handler/handler.go | 2 +- builder/build/code_build.go | 203 +++++++++----------------- builder/job/job.go | 16 ++ cmd/api/option/option.go | 2 + grctl/cmd/build.go | 189 ++++++++++++++++++++++++ localbuild.sh | 6 +- 10 files changed, 480 insertions(+), 138 deletions(-) diff --git a/api/api/api_interface.go b/api/api/api_interface.go index 401dfb439..28bfc5957 100644 --- a/api/api/api_interface.go +++ b/api/api/api_interface.go @@ -25,6 +25,11 @@ import ( // ClusterInterface - type ClusterInterface interface { GetClusterInfo(w http.ResponseWriter, r *http.Request) + MavenSettingList(w http.ResponseWriter, r *http.Request) + MavenSettingAdd(w http.ResponseWriter, r *http.Request) + MavenSettingUpdate(w http.ResponseWriter, r *http.Request) + MavenSettingDelete(w http.ResponseWriter, r *http.Request) + MavenSettingDetail(w http.ResponseWriter, r *http.Request) } //TenantInterface interface diff --git a/api/api_routers/version2/v2Routers.go b/api/api_routers/version2/v2Routers.go index 7a858ffa4..9e738fe27 100644 --- a/api/api_routers/version2/v2Routers.go +++ b/api/api_routers/version2/v2Routers.go @@ -82,6 +82,11 @@ func (v2 *V2) eventsRouter() chi.Router { func (v2 *V2) clusterRouter() chi.Router { r := chi.NewRouter() r.Get("/", controller.GetManager().GetClusterInfo) + r.Get("/builder/mavensetting", controller.GetManager().MavenSettingList) + r.Post("/builder/mavensetting", controller.GetManager().MavenSettingAdd) + r.Get("/builder/mavensetting/{name}", controller.GetManager().MavenSettingDetail) + r.Put("/builder/mavensetting/{name}", controller.GetManager().MavenSettingUpdate) + r.Delete("/builder/mavensetting/{name}", controller.GetManager().MavenSettingDelete) return r } diff --git a/api/controller/cluster.go b/api/controller/cluster.go index 2173f23b2..3a77d75ce 100644 --- a/api/controller/cluster.go +++ b/api/controller/cluster.go @@ -22,6 +22,7 @@ import ( "net/http" "github.com/Sirupsen/logrus" + "github.com/go-chi/chi" "github.com/goodrain/rainbond/api/handler" httputil "github.com/goodrain/rainbond/util/http" @@ -42,3 +43,61 @@ func (t *ClusterController) GetClusterInfo(w http.ResponseWriter, r *http.Reques httputil.ReturnSuccess(r, w, nodes) } + +//MavenSettingList maven setting list +func (t *ClusterController) MavenSettingList(w http.ResponseWriter, r *http.Request) { + httputil.ReturnSuccess(r, w, handler.GetClusterHandler().MavenSettingList()) +} + +//MavenSettingAdd maven setting add +func (t *ClusterController) MavenSettingAdd(w http.ResponseWriter, r *http.Request) { + var set handler.MavenSetting + if ok := httputil.ValidatorRequestStructAndErrorResponse(r, w, &set, nil); !ok { + return + } + if err := handler.GetClusterHandler().MavenSettingAdd(&set); err != nil { + err.Handle(r, w) + return + } + httputil.ReturnSuccess(r, w, &set) +} + +//MavenSettingUpdate maven setting file update +func (t *ClusterController) MavenSettingUpdate(w http.ResponseWriter, r *http.Request) { + type SettingUpdate struct { + Content string `json:"content" validate:"required"` + } + var su SettingUpdate + if ok := httputil.ValidatorRequestStructAndErrorResponse(r, w, &su, nil); !ok { + return + } + set := &handler.MavenSetting{ + Name: chi.URLParam(r, "name"), + Content: su.Content, + } + if err := handler.GetClusterHandler().MavenSettingUpdate(set); err != nil { + err.Handle(r, w) + return + } + httputil.ReturnSuccess(r, w, set) +} + +//MavenSettingDelete maven setting file delete +func (t *ClusterController) MavenSettingDelete(w http.ResponseWriter, r *http.Request) { + err := handler.GetClusterHandler().MavenSettingDelete(chi.URLParam(r, "name")) + if err != nil { + err.Handle(r, w) + return + } + httputil.ReturnSuccess(r, w, nil) +} + +//MavenSettingDetail maven setting file delete +func (t *ClusterController) MavenSettingDetail(w http.ResponseWriter, r *http.Request) { + c, err := handler.GetClusterHandler().MavenSettingDetail(chi.URLParam(r, "name")) + if err != nil { + err.Handle(r, w) + return + } + httputil.ReturnSuccess(r, w, c) +} diff --git a/api/handler/cluster.go b/api/handler/cluster.go index 8756a7c57..73af5f103 100644 --- a/api/handler/cluster.go +++ b/api/handler/cluster.go @@ -3,11 +3,16 @@ package handler import ( "fmt" "runtime" + "strings" + "time" "github.com/Sirupsen/logrus" "github.com/goodrain/rainbond/api/model" + "github.com/goodrain/rainbond/api/util" + "github.com/goodrain/rainbond/builder/parser/code" "github.com/shirou/gopsutil/disk" corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/fields" "k8s.io/client-go/kubernetes" @@ -16,16 +21,23 @@ import ( // ClusterHandler - type ClusterHandler interface { GetClusterInfo() (*model.ClusterResource, error) + MavenSettingAdd(ms *MavenSetting) *util.APIHandleError + MavenSettingList() (re []MavenSetting) + MavenSettingUpdate(ms *MavenSetting) *util.APIHandleError + MavenSettingDelete(name string) *util.APIHandleError + MavenSettingDetail(name string) (*MavenSetting, *util.APIHandleError) } // NewClusterHandler - -func NewClusterHandler(clientset *kubernetes.Clientset) ClusterHandler { +func NewClusterHandler(clientset *kubernetes.Clientset, RbdNamespace string) ClusterHandler { return &clusterAction{ + namespace: RbdNamespace, clientset: clientset, } } type clusterAction struct { + namespace string clientset *kubernetes.Clientset } @@ -184,3 +196,120 @@ func (c *clusterAction) listPods(nodeName string) (pods []corev1.Pod, err error) return podList.Items, nil } + +//MavenSetting maven setting +type MavenSetting struct { + Name string `json:"name" validate:"required"` + CreateTime string `json:"create_time"` + UpdateTime string `json:"update_time"` + Content string `json:"content" validate:"required"` +} + +//MavenSettingList maven setting list +func (c *clusterAction) MavenSettingList() (re []MavenSetting) { + cms, err := c.clientset.CoreV1().ConfigMaps(c.namespace).List(metav1.ListOptions{ + LabelSelector: "configtype=mavensetting", + }) + if err != nil { + logrus.Errorf("list maven setting config list failure %s", err.Error()) + } + for _, sm := range cms.Items { + info := strings.Split(sm.Name, "-") + if len(info) > 0 { + re = append(re, MavenSetting{ + Name: info[len(info)-1], + CreateTime: sm.CreationTimestamp.Format(time.RFC3339), + UpdateTime: sm.Labels["updateTime"], + Content: sm.Data["mavensetting"], + }) + } + } + return +} + +//MavenSettingAdd maven setting add +func (c *clusterAction) MavenSettingAdd(ms *MavenSetting) *util.APIHandleError { + realName := strings.ToLower(fmt.Sprintf("%s-%s", code.JavaMaven, ms.Name)) + config := &corev1.ConfigMap{} + config.Name = realName + config.Namespace = c.namespace + config.Labels = map[string]string{ + "creator": "Rainbond", + "configtype": "mavensetting", + } + config.Annotations = map[string]string{ + "updateTime": time.Now().Format(time.RFC3339), + } + config.Data = map[string]string{ + "mavensetting": ms.Content, + } + _, err := c.clientset.CoreV1().ConfigMaps(c.namespace).Create(config) + if err != nil { + if apierrors.IsAlreadyExists(err) { + return &util.APIHandleError{Code: 400, Err: fmt.Errorf("setting name is exist")} + } + logrus.Errorf("create maven setting configmap failure %s", err.Error()) + return &util.APIHandleError{Code: 500, Err: fmt.Errorf("create setting config failure")} + } + ms.CreateTime = time.Now().Format(time.RFC3339) + ms.UpdateTime = time.Now().Format(time.RFC3339) + return nil +} + +//MavenSettingUpdate maven setting file update +func (c *clusterAction) MavenSettingUpdate(ms *MavenSetting) *util.APIHandleError { + realName := strings.ToLower(fmt.Sprintf("%s-%s", code.JavaMaven, ms.Name)) + sm, err := c.clientset.CoreV1().ConfigMaps(c.namespace).Get(realName, metav1.GetOptions{}) + if err != nil { + if apierrors.IsNotFound(err) { + return &util.APIHandleError{Code: 404, Err: fmt.Errorf("setting name is not exist")} + } + logrus.Errorf("get maven setting config list failure %s", err.Error()) + return &util.APIHandleError{Code: 400, Err: fmt.Errorf("get setting failure")} + } + if sm.Data == nil { + sm.Data = make(map[string]string) + } + if sm.Annotations == nil { + sm.Annotations = make(map[string]string) + } + sm.Data["mavensetting"] = ms.Content + sm.Annotations["updateTime"] = time.Now().Format(time.RFC3339) + if _, err := c.clientset.CoreV1().ConfigMaps(c.namespace).Update(sm); err != nil { + logrus.Errorf("update maven setting configmap failure %s", err.Error()) + return &util.APIHandleError{Code: 500, Err: fmt.Errorf("update setting config failure")} + } + ms.UpdateTime = sm.Annotations["updateTime"] + ms.CreateTime = sm.CreationTimestamp.Format(time.RFC3339) + return nil +} + +//MavenSettingDelete maven setting file delete +func (c *clusterAction) MavenSettingDelete(name string) *util.APIHandleError { + realName := strings.ToLower(fmt.Sprintf("%s-%s", code.JavaMaven, name)) + err := c.clientset.CoreV1().ConfigMaps(c.namespace).Delete(realName, &metav1.DeleteOptions{}) + if err != nil { + if apierrors.IsNotFound(err) { + return &util.APIHandleError{Code: 404, Err: fmt.Errorf("setting not found")} + } + logrus.Errorf("delete maven setting config list failure %s", err.Error()) + return &util.APIHandleError{Code: 500, Err: fmt.Errorf("setting delete failure")} + } + return nil +} + +//MavenSettingDetail maven setting file delete +func (c *clusterAction) MavenSettingDetail(name string) (*MavenSetting, *util.APIHandleError) { + realName := strings.ToLower(fmt.Sprintf("%s-%s", code.JavaMaven, name)) + sm, err := c.clientset.CoreV1().ConfigMaps(c.namespace).Get(realName, metav1.GetOptions{}) + if err != nil { + logrus.Errorf("get maven setting config failure %s", err.Error()) + return nil, &util.APIHandleError{Code: 404, Err: fmt.Errorf("setting not found")} + } + return &MavenSetting{ + Name: sm.Name, + CreateTime: sm.CreationTimestamp.Format(time.RFC3339), + UpdateTime: sm.Annotations["updateTime"], + Content: sm.Data["mavensetting"], + }, nil +} diff --git a/api/handler/handler.go b/api/handler/handler.go index 6d99b370c..268df90e8 100644 --- a/api/handler/handler.go +++ b/api/handler/handler.go @@ -68,7 +68,7 @@ func InitHandle(conf option.Config, batchOperationHandler = CreateBatchOperationHandler(mqClient, operationHandler) defaultAppRestoreHandler = NewAppRestoreHandler() defPodHandler = NewPodHandler(statusCli) - defClusterHandler = NewClusterHandler(kubeClient) + defClusterHandler = NewClusterHandler(kubeClient, conf.RbdNamespace) defaultVolumeTypeHandler = CreateVolumeTypeManger(statusCli) defaultEtcdHandler = NewEtcdHandler(etcdcli) diff --git a/builder/build/code_build.go b/builder/build/code_build.go index c459a4b1a..b187d7eff 100644 --- a/builder/build/code_build.go +++ b/builder/build/code_build.go @@ -33,11 +33,11 @@ import ( "github.com/Sirupsen/logrus" "github.com/docker/docker/api/types" - "github.com/docker/docker/client" "github.com/eapache/channels" "github.com/fsnotify/fsnotify" "github.com/goodrain/rainbond/builder" jobc "github.com/goodrain/rainbond/builder/job" + "github.com/goodrain/rainbond/builder/parser/code" "github.com/goodrain/rainbond/builder/sources" "github.com/goodrain/rainbond/event" "github.com/goodrain/rainbond/util" @@ -277,23 +277,6 @@ func (s *slugBuild) runBuildJob(re *Request) error { }() name := fmt.Sprintf("%s-%s", re.ServiceID, re.DeployVersion) namespace := re.RbdNamespace - envs := []corev1.EnvVar{ - {Name: "SLUG_VERSION", Value: re.DeployVersion}, - {Name: "SERVICE_ID", Value: re.ServiceID}, - {Name: "TENANT_ID", Value: re.TenantID}, - {Name: "LANGUAGE", Value: re.Lang.String()}, - } - for k, v := range re.BuildEnvs { - envs = append(envs, corev1.EnvVar{Name: k, Value: v}) - if k == "PROC_ENV" { - var mapdata = make(map[string]interface{}) - if err := json.Unmarshal([]byte(v), &mapdata); err == nil { - if runtime, ok := mapdata["runtimes"]; ok { - envs = append(envs, corev1.EnvVar{Name: "RUNTIME", Value: runtime.(string)}) - } - } - } - } job := corev1.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: name, @@ -304,7 +287,35 @@ func (s *slugBuild) runBuildJob(re *Request) error { }, }, } - + envs := []corev1.EnvVar{ + {Name: "SLUG_VERSION", Value: re.DeployVersion}, + {Name: "SERVICE_ID", Value: re.ServiceID}, + {Name: "TENANT_ID", Value: re.TenantID}, + {Name: "LANGUAGE", Value: re.Lang.String()}, + } + var mavenSettingName string + for k, v := range re.BuildEnvs { + if k == "MAVEN_SETTING_NAME" { + mavenSettingName = v + continue + } + if k == "PROCFILE" { + if !strings.HasPrefix(v, "web:") { + v = "web: " + v + } else if v[4] != ' ' { + v = "web: " + v[4:] + } + } + envs = append(envs, corev1.EnvVar{Name: k, Value: v}) + if k == "PROC_ENV" { + var mapdata = make(map[string]interface{}) + if err := json.Unmarshal([]byte(v), &mapdata); err == nil { + if runtime, ok := mapdata["runtimes"]; ok { + envs = append(envs, corev1.EnvVar{Name: "RUNTIME", Value: runtime.(string)}) + } + } + } + } podSpec := corev1.PodSpec{RestartPolicy: corev1.RestartPolicyOnFailure} // only support never and onfailure // schedule builder if re.CacheMode == "hostpath" { @@ -337,10 +348,14 @@ func (s *slugBuild) runBuildJob(re *Request) error { VolumeSource: re.CacheVolumeSource(), }, } - - container := corev1.Container{Name: name, Image: builder.BUILDERIMAGENAME, Stdin: true, StdinOnce: true} - container.Env = envs - container.Args = []string{"local"} + container := corev1.Container{ + Name: name, + Image: builder.BUILDERIMAGENAME, + Stdin: true, + StdinOnce: true, + Env: envs, + Args: []string{"local"}, + } slugSubPath := strings.TrimPrefix(re.TGZDir, "/grdata/") logrus.Debugf("sourceTarFileName is: %s", sourceTarFileName) sourceTarPath := strings.TrimPrefix(sourceTarFileName, "/cache/") @@ -362,6 +377,38 @@ func (s *slugBuild) runBuildJob(re *Request) error { SubPath: sourceTarPath, }, } + //set maven setting + if mavenSettingName != "" && re.Lang.String() == code.JavaMaven.String() { + if setting := jobc.GetJobController().GetLanguageBuildSetting(code.JavaMaven, mavenSettingName); setting != "" { + podSpec.Volumes = append(podSpec.Volumes, corev1.Volume{ + Name: "mavensetting", + VolumeSource: corev1.VolumeSource{ + ConfigMap: &corev1.ConfigMapVolumeSource{ + LocalObjectReference: corev1.LocalObjectReference{ + Name: setting, + }, + }, + }, + }) + mountPath := "/etc/maven/setting.xml" + container.VolumeMounts = append(container.VolumeMounts, corev1.VolumeMount{ + MountPath: mountPath, + SubPath: "mavensetting", + Name: "mavensetting", + }) + container.Env = append(container.Env, corev1.EnvVar{ + Name: "MAVEN_SETTINGS_PATH", + Value: mountPath, + }) + container.Env = append(container.Env, corev1.EnvVar{ + Name: "MAVEN_MIRROR_DISABLE", + Value: "true", + }) + logrus.Infof("set maven setting config %s success", mavenSettingName) + } else { + logrus.Warnf("maven setting config %s not found", mavenSettingName) + } + } podSpec.Containers = append(podSpec.Containers, container) for _, ha := range re.HostAlias { podSpec.HostAliases = append(podSpec.HostAliases, corev1.HostAlias{IP: ha.IP, Hostnames: ha.Hostnames}) @@ -425,116 +472,6 @@ func (s *slugBuild) waitingComplete(re *Request, reChan *channels.RingChannel) ( } } -//runBuildContainer The deprecated -func (s *slugBuild) runBuildContainer(re *Request) error { - envs := []*sources.KeyValue{ - &sources.KeyValue{Key: "SLUG_VERSION", Value: re.DeployVersion}, - &sources.KeyValue{Key: "SERVICE_ID", Value: re.ServiceID}, - &sources.KeyValue{Key: "TENANT_ID", Value: re.TenantID}, - &sources.KeyValue{Key: "LANGUAGE", Value: re.Lang.String()}, - } - for k, v := range re.BuildEnvs { - envs = append(envs, &sources.KeyValue{Key: k, Value: v}) - if k == "PROC_ENV" { - var mapdata = make(map[string]interface{}) - if err := json.Unmarshal([]byte(v), &mapdata); err == nil { - if runtime, ok := mapdata["runtimes"]; ok { - envs = append(envs, &sources.KeyValue{Key: "RUNTIME", Value: runtime.(string)}) - } - } - } - } - containerConfig := &sources.ContainerConfig{ - Metadata: &sources.ContainerMetadata{ - Name: re.ServiceID[:8] + "_" + re.DeployVersion, - }, - Image: &sources.ImageSpec{ - Image: builder.BUILDERIMAGENAME, - }, - Mounts: []*sources.Mount{ - &sources.Mount{ - ContainerPath: "/tmp/cache", - HostPath: re.CacheDir, - Readonly: false, - }, - &sources.Mount{ - ContainerPath: "/tmp/slug", - HostPath: s.tgzDir, - Readonly: false, - }, - }, - Envs: envs, - Stdin: true, - StdinOnce: true, - AttachStdin: true, - AttachStdout: true, - AttachStderr: true, - NetworkConfig: &sources.NetworkConfig{ - NetworkMode: "host", - }, - Args: []string{"local"}, - ExtraHosts: re.ExtraHosts, - } - sourceTarFileName, err := s.getSourceCodeTarFile(re) - if err != nil { - return fmt.Errorf("create source code tar file error:%s", err.Error()) - } - reader, err := os.OpenFile(sourceTarFileName, os.O_RDONLY, 0755) - if err != nil { - return fmt.Errorf("open source code tar file error:%s", err.Error()) - } - defer func() { - reader.Close() - os.Remove(reader.Name()) - }() - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - containerService := sources.CreateDockerService(ctx, re.DockerClient) - containerID, err := containerService.CreateContainer(containerConfig) - if err != nil { - if client.IsErrNotFound(err) { - // we don't want to write to stdout anything apart from container.ID - if _, err = sources.ImagePull(re.DockerClient, containerConfig.Image.Image, builder.REGISTRYUSER, builder.REGISTRYPASS, re.Logger, 20); err != nil { - return fmt.Errorf("pull builder container image error:%s", err.Error()) - } - // Retry - containerID, err = containerService.CreateContainer(containerConfig) - } - //The container already exists. - if err != nil && strings.Contains(err.Error(), "is already in use by container") { - //remove exist container - containerService.RemoveContainer(containerID) - // Retry - containerID, err = containerService.CreateContainer(containerConfig) - } - if err != nil { - return fmt.Errorf("create builder container failure %s", err.Error()) - } - } - errchan := make(chan error, 1) - writer := re.Logger.GetWriter("builder", "info") - close, err := containerService.AttachContainer(containerID, true, true, true, reader, writer, writer, &errchan) - if err != nil { - containerService.RemoveContainer(containerID) - return fmt.Errorf("attach builder container error:%s", err.Error()) - } - defer close() - statuschan := containerService.WaitExitOrRemoved(containerID, true) - //start the container - if err := containerService.StartContainer(containerID); err != nil { - containerService.RemoveContainer(containerID) - return fmt.Errorf("start builder container error:%s", err.Error()) - } - if err := <-errchan; err != nil { - logrus.Debugf("Error hijack: %s", err) - } - status := <-statuschan - if status != 0 { - return &ErrorBuild{Code: status} - } - return nil -} - func (s *slugBuild) setImagePullSecretsForPod(pod *corev1.Pod) { imagePullSecretName := os.Getenv("IMAGE_PULL_SECRET") if imagePullSecretName == "" { diff --git a/builder/job/job.go b/builder/job/job.go index b4426f4af..032a800d7 100644 --- a/builder/job/job.go +++ b/builder/job/job.go @@ -21,12 +21,15 @@ package job import ( "bufio" "context" + "fmt" "io" + "strings" "sync" "time" "github.com/Sirupsen/logrus" "github.com/eapache/channels" + "github.com/goodrain/rainbond/builder/parser/code" corev1 "k8s.io/api/core/v1" k8sErrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -43,6 +46,7 @@ type Controller interface { GetJob(string) (*corev1.Pod, error) GetServiceJobs(serviceID string) ([]*corev1.Pod, error) DeleteJob(job string) + GetLanguageBuildSetting(lang code.Lang, name string) string } type controller struct { KubeClient kubernetes.Interface @@ -228,3 +232,15 @@ func (c *controller) DeleteJob(job string) { c.jobContainerStatus.Delete(job) logrus.Infof("delete job %s finish", job) } + +func (c *controller) GetLanguageBuildSetting(lang code.Lang, name string) string { + cname := strings.ToLower(fmt.Sprintf("%s-%s", lang, name)) + config, err := c.KubeClient.CoreV1().ConfigMaps(c.namespace).Get(cname, metav1.GetOptions{}) + if err != nil { + logrus.Errorf("get configmap %s failure %s", cname, err.Error()) + } + if config != nil { + return cname + } + return "" +} diff --git a/cmd/api/option/option.go b/cmd/api/option/option.go index fb674b61f..ae7a4cc32 100644 --- a/cmd/api/option/option.go +++ b/cmd/api/option/option.go @@ -59,6 +59,7 @@ type Config struct { LogPath string KuberentesDashboardAPI string KubeConfigPath string + RbdNamespace string } //APIServer apiserver server @@ -109,6 +110,7 @@ func (a *APIServer) AddFlags(fs *pflag.FlagSet) { fs.StringVar(&a.LogPath, "log-path", "/grdata/logs", "Where Docker log files and event log files are stored.") fs.StringVar(&a.KubeConfigPath, "kube-config", "", "kube config file path, No setup is required to run in a cluster.") fs.StringVar(&a.KuberentesDashboardAPI, "k8s-dashboard-api", "kubernetes-dashboard.rbd-system:443", "The service DNS name of Kubernetes dashboard. Default to kubernetes-dashboard.kubernetes-dashboard") + fs.StringVar(&a.RbdNamespace, "rbd-namespace", "rbd-system", "rbd component namespace") } //SetLog 设置log diff --git a/grctl/cmd/build.go b/grctl/cmd/build.go index fb5a20758..ebd76b0db 100644 --- a/grctl/cmd/build.go +++ b/grctl/cmd/build.go @@ -21,18 +21,24 @@ package cmd import ( "context" "fmt" + "io/ioutil" "os" "os/exec" "path" "strings" + "time" "github.com/Sirupsen/logrus" + "github.com/apcera/termtables" "github.com/docker/docker/client" "github.com/goodrain/rainbond/builder" "github.com/goodrain/rainbond/builder/parser/code" "github.com/goodrain/rainbond/builder/sources" + "github.com/goodrain/rainbond/grctl/clients" "github.com/goodrain/rainbond/util" "github.com/urfave/cli" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) //NewSourceBuildCmd cmd for source build test @@ -106,6 +112,189 @@ func NewSourceBuildCmd() cli.Command { cmd.Run() }, }, + cli.Command{ + Name: "maven-setting", + Usage: "maven setting config file manage", + Subcommands: []cli.Command{ + cli.Command{ + Name: "list", + Flags: []cli.Flag{ + cli.StringFlag{ + Name: "namespace,ns", + Usage: "rainbond default namespace", + Value: "rbd-system", + }, + }, + Usage: "list maven setting config file manage", + Action: func(ctx *cli.Context) { + Common(ctx) + namespace := ctx.String("namespace") + cms, err := clients.K8SClient.CoreV1().ConfigMaps(namespace).List(metav1.ListOptions{ + LabelSelector: "configtype=mavensetting", + }) + if err != nil { + showError(err.Error()) + } + runtable := termtables.CreateTable() + runtable.AddHeaders("Name", "CreateTime", "UpdateTime") + for _, cm := range cms.Items { + info := strings.Split(cm.Name, "-") + var updateTime = "-" + if cm.Annotations != nil { + updateTime = cm.Annotations["updateTime"] + } + if len(info) > 0 { + runtable.AddRow(info[len(info)-1], cm.CreationTimestamp.Format(time.RFC3339), updateTime) + } + } + fmt.Println(runtable.Render()) + }, + }, + cli.Command{ + Name: "get", + Flags: []cli.Flag{ + cli.StringFlag{ + Name: "namespace,ns", + Usage: "rainbond default namespace", + Value: "rbd-system", + }, + }, + Usage: "get maven setting config file manage", + Action: func(ctx *cli.Context) { + Common(ctx) + name := ctx.Args().First() + if name == "" { + showError("Please specify the task pod name") + } + namespace := ctx.String("namespace") + realName := strings.ToLower(fmt.Sprintf("%s-%s", code.JavaMaven, name)) + cm, err := clients.K8SClient.CoreV1().ConfigMaps(namespace).Get(realName, metav1.GetOptions{}) + if err != nil { + showError(err.Error()) + } + fmt.Println(cm.Data["mavensetting"]) + }, + }, + cli.Command{ + Name: "update", + Usage: "update maven setting config file manage", + Flags: []cli.Flag{ + cli.StringFlag{ + Name: "file,f", + Usage: "define maven setting file", + Value: "./setting.xml", + }, + cli.StringFlag{ + Name: "namespace,ns", + Usage: "rainbond default namespace", + Value: "rbd-system", + }, + }, + Action: func(ctx *cli.Context) { + Common(ctx) + name := ctx.Args().First() + if name == "" { + showError("Please specify the task pod name") + } + namespace := ctx.String("namespace") + realName := strings.ToLower(fmt.Sprintf("%s-%s", code.JavaMaven, name)) + cm, err := clients.K8SClient.CoreV1().ConfigMaps(namespace).Get(realName, metav1.GetOptions{}) + if err != nil { + showError(err.Error()) + } + body, err := ioutil.ReadFile(ctx.String("f")) + if err != nil { + showError(err.Error()) + } + if cm.Data == nil { + cm.Data = make(map[string]string) + } + if cm.Annotations == nil { + cm.Annotations = make(map[string]string) + } + cm.Data["mavensetting"] = string(body) + cm.Annotations["updateTime"] = time.Now().Format(time.RFC3339) + _, err = clients.K8SClient.CoreV1().ConfigMaps(namespace).Update(cm) + if err != nil { + showError(err.Error()) + } + fmt.Println("Update Success") + }, + }, + cli.Command{ + Name: "add", + Usage: "add maven setting config file manage", + Flags: []cli.Flag{ + cli.StringFlag{ + Name: "file,f", + Usage: "define maven setting file", + Value: "./setting.xml", + }, + cli.StringFlag{ + Name: "namespace,ns", + Usage: "rainbond default namespace", + Value: "rbd-system", + }, + }, + Action: func(ctx *cli.Context) { + Common(ctx) + name := ctx.Args().First() + if name == "" { + showError("Please specify the task pod name") + } + namespace := ctx.String("namespace") + realName := strings.ToLower(fmt.Sprintf("%s-%s", code.JavaMaven, name)) + body, err := ioutil.ReadFile(ctx.String("f")) + if err != nil { + showError(err.Error()) + } + config := &corev1.ConfigMap{} + config.Name = realName + config.Namespace = namespace + config.Labels = map[string]string{ + "creator": "Rainbond", + "configtype": "mavensetting", + } + config.Annotations = map[string]string{ + "updateTime": time.Now().Format(time.RFC3339), + } + config.Data = map[string]string{ + "mavensetting": string(body), + } + _, err = clients.K8SClient.CoreV1().ConfigMaps(namespace).Create(config) + if err != nil { + showError(err.Error()) + } + fmt.Println("Add Success") + }, + }, + cli.Command{ + Name: "delete", + Usage: "delete maven setting config file manage", + Flags: []cli.Flag{ + cli.StringFlag{ + Name: "namespace,ns", + Usage: "rainbond default namespace", + Value: "rbd-system", + }, + }, + Action: func(ctx *cli.Context) { + Common(ctx) + name := ctx.Args().First() + if name == "" { + showError("Please specify the task pod name") + } + namespace := ctx.String("namespace") + realName := strings.ToLower(fmt.Sprintf("%s-%s", code.JavaMaven, name)) + err := clients.K8SClient.CoreV1().ConfigMaps(namespace).Delete(realName, &metav1.DeleteOptions{}) + if err != nil { + showError(err.Error()) + } + fmt.Println("Delete Success") + }, + }, + }, + }, }, Name: "build", Usage: "Commands related to building source code", diff --git a/localbuild.sh b/localbuild.sh index fea8c2a1f..6c5da3502 100755 --- a/localbuild.sh +++ b/localbuild.sh @@ -23,7 +23,7 @@ function localbuild() { for item in "${build_items[@]}" do echo "build local ${item}" - go build -ldflags "-w -s -X github.com/goodrain/rainbond/cmd.version=${release_desc}" -o _output/${GOOS}/${VERSION}/rainbond-$item ./cmd/$item + go build -ldflags "-X github.com/goodrain/rainbond/cmd.version=${release_desc}" -o _output/${GOOS}/${VERSION}/rainbond-$item ./cmd/$item done else echo "build local $1 ${VERSION}" @@ -32,11 +32,11 @@ function localbuild() { if [ "$GOOS" = "windows" ];then outputname="_output/${GOOS}/${VERSION}/rainbond-$1.exe" fi - ldflags="-w -s -X github.com/goodrain/rainbond/cmd.version=${release_desc}" + ldflags="-X github.com/goodrain/rainbond/cmd.version=${release_desc}" if [ "$STATIC" = "true" ];then ldflags="${ldflags} -extldflags '-static'" fi - CGO_ENABLED=1 go build -v -ldflags "${ldflags}" -o ${outputname} ./cmd/$1 + go build -v -ldflags "${ldflags}" -o ${outputname} ./cmd/$1 fi }