🤬
Revision indexing in progress... (symbol navigation in revisions will be accurate after indexed)
  • ■ ■ ■ ■ ■
    pkg/constant/message.go
    skipped 19 lines
    20 20  //message type
    21 21  const (
    22 22   ClusterInstall = "CLUSTER_INSTALL"
     23 + ClusterImport = "CLUSTER_IMPORT"
    23 24   ClusterUnInstall = "CLUSTER_UN_INSTALL"
    24 25   ClusterUpgrade = "CLUSTER_UPGRADE"
    25 26   ClusterDelete = "CLUSTER_DELETE"
    skipped 14 lines
  • ■ ■ ■ ■ ■
    pkg/constant/rbac.go
    skipped 191 lines
    192 192   "/api/v1/settings",
    193 193   "/api/v1/settings/{**}",
    194 194   "/api/v1/settings/{**}/{**}",
     195 + "/api/v1/settings/registry/change/password",
    195 196   },
    196 197   Method: []string{"POST", "DELETE", "PUT", "PATCH"},
    197 198   Permission: &grbac.Permission{
    skipped 84 lines
  • ■ ■ ■ ■ ■
    pkg/constant/system_log.go
    skipped 107 lines
    108 108   DELETE_CREDENTIALS = "删除凭证|Delete credentials"
    109 109   CREATE_REGISTRY = "添加仓库信息|Create registry"
    110 110   UPDATE_REGISTRY = "更新仓库信息|Delete registry"
     111 + UPDATE_NEXUS_PASSWORD = "更新 Nexus 仓库密码|Update nexus password"
    111 112   DELETE_REGISTRY = "删除仓库信息|Delete registry"
    112 113   CREATE_BACKUP_ACCOUNT = "添加备份账号|Create backup account"
    113 114   UPDATE_BACKUP_ACCOUNT = "修改备份账号信息|Update backup account information"
    skipped 5 lines
  • ■ ■ ■ ■ ■ ■
    pkg/controller/cluster.go
    skipped 87 lines
    88 88   }
    89 89  }
    90 90   
     91 +// Search Cluster
     92 +// @Tags clusters
     93 +// @Summary Search cluster
     94 +// @Description 过滤集群
     95 +// @Accept json
     96 +// @Produce json
     97 +// @Param conditions body condition.Conditions true "conditions"
     98 +// @Success 200 {object} page.Page
     99 +// @Security ApiKeyAuth
     100 +// @Router /clusters/search [post]
    91 101  func (c ClusterController) PostSearch() (*dto.ClusterPage, error) {
    92 102   page, _ := c.Ctx.Values().GetBool("page")
    93 103   var conditions condition.Conditions
    skipped 101 lines
    195 205   return c.ClusterInitService.Init(name)
    196 206  }
    197 207   
     208 +// Load Cluster Info for import
     209 +// @Tags clusters
     210 +// @Summary Load cluster info
     211 +// @Description Upgrade a cluster
     212 +// @Param request body dto.ClusterLoad true "request"
     213 +// @Accept json
     214 +// @Produce json
     215 +// @Success 200 {object} dto.ClusterLoadInfo
     216 +// @Security ApiKeyAuth
     217 +// @Router /clusters/load [post]
    198 218  func (c ClusterController) PostLoad() (dto.ClusterLoadInfo, error) {
    199 219   var req dto.ClusterLoad
    200 220   var data dto.ClusterLoadInfo
    skipped 129 lines
    330 350   return tool, nil
    331 351  }
    332 352   
     353 +func (c ClusterController) PostToolSyncBy(clusterName string) (*[]dto.ClusterTool, error) {
     354 + cts, err := c.ClusterToolService.SyncStatus(clusterName)
     355 + if err != nil {
     356 + logger.Log.Info(fmt.Sprintf("%+v", err))
     357 + return nil, err
     358 + }
     359 + 
     360 + return &cts, nil
     361 +}
     362 + 
    333 363  func (c ClusterController) PostToolEnableBy(clusterName string) (*dto.ClusterTool, error) {
    334 364   var req dto.ClusterTool
    335 365   if err := c.Ctx.ReadJSON(&req); err != nil {
    skipped 48 lines
    384 414  // @Tags clusters
    385 415  // @Summary Delete a cluster
    386 416  // @Description delete a cluster by name
     417 +// @Param force query string true "是否强制(true, false)"
     418 +// @Param uninstall query string true "是否卸载(true, false)"
    387 419  // @Accept json
    388 420  // @Produce json
    389 421  // @Security ApiKeyAuth
    skipped 12 lines
    402 434  // @Tags clusters
    403 435  // @Summary Import a cluster
    404 436  // @Description import a cluster
     437 +// @Param request body dto.ClusterImport true "request"
    405 438  // @Accept json
    406 439  // @Produce json
    407 440  // @Security ApiKeyAuth
    skipped 248 lines
  • ■ ■ ■ ■ ■ ■
    pkg/controller/system_setting.go
    skipped 1 lines
    2 2   
    3 3  import (
    4 4   "errors"
     5 + 
    5 6   "github.com/KubeOperator/KubeOperator/pkg/controller/condition"
    6 7   
    7 8   "github.com/KubeOperator/KubeOperator/pkg/constant"
    skipped 114 lines
    122 123   return err
    123 124   }
    124 125   return nil
     126 +}
     127 + 
     128 +// Change Nexus Password
     129 +// @Tags SystemSetting
     130 +// @Summary Change user password
     131 +// @Description 更新 Nexus 密码
     132 +// @Accept json
     133 +// @Produce json
     134 +// @Param request body dto.RepoChangePassword true "request"
     135 +// @Success 200
     136 +// @Security ApiKeyAuth
     137 +// @Router /settings/registry/change/password [post]
     138 +func (s *SystemSettingController) PostRegistryChangePassword() error {
     139 + var req dto.RepoChangePassword
     140 + err := s.Ctx.ReadJSON(&req)
     141 + if err != nil {
     142 + return err
     143 + }
     144 + validate := validator.New()
     145 + err = validate.Struct(req)
     146 + if err != nil {
     147 + return err
     148 + }
     149 + err = s.SystemSettingService.ChangePassword(req)
     150 + if err != nil {
     151 + return err
     152 + }
     153 + 
     154 + operator := s.Ctx.Values().GetString("operator")
     155 + go kolog.Save(operator, constant.UPDATE_NEXUS_PASSWORD, "-")
     156 + 
     157 + return err
    125 158  }
    126 159   
    127 160  // List Registry
    skipped 172 lines
  • ■ ■ ■ ■ ■ ■
    pkg/dto/system_registry.go
    skipped 35 lines
    36 36   Items []SystemRegistry `json:"items" validate:"required"`
    37 37  }
    38 38   
     39 +type RepoChangePassword struct {
     40 + ID string `json:"id"`
     41 + Password string `json:"password"`
     42 + Original string `json:"original"`
     43 +}
     44 + 
  • ■ ■ ■ ■ ■ ■
    pkg/router/proxy/prometheus.go
     1 +package proxy
     2 + 
     3 +import (
     4 + "crypto/tls"
     5 + "fmt"
     6 + "net/http"
     7 + "net/http/httputil"
     8 + "net/url"
     9 + 
     10 + "github.com/KubeOperator/KubeOperator/pkg/constant"
     11 + "github.com/kataras/iris/v12/context"
     12 +)
     13 + 
     14 +func PrometheusProxy(ctx context.Context) {
     15 + clusterName := ctx.Params().Get("cluster_name")
     16 + proxyPath := ctx.Params().Get("p")
     17 + if clusterName == "" {
     18 + _, _ = ctx.JSON(http.StatusBadRequest)
     19 + return
     20 + }
     21 + endpoint, err := clusterService.GetRouterEndpoint(clusterName)
     22 + if err != nil {
     23 + _, _ = ctx.JSON(http.StatusInternalServerError)
     24 + return
     25 + }
     26 + host := fmt.Sprintf(constant.DefaultPrometheusIngress)
     27 + u, err := url.Parse(fmt.Sprintf("http://%s", endpoint.Address))
     28 + if err != nil {
     29 + _, _ = ctx.JSON(http.StatusInternalServerError)
     30 + return
     31 + }
     32 + proxy := httputil.NewSingleHostReverseProxy(u)
     33 + proxy.Transport = &http.Transport{
     34 + TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
     35 + }
     36 + req := ctx.Request()
     37 + req.Host = host
     38 + req.URL.Path = proxyPath
     39 + proxy.ServeHTTP(ctx.ResponseWriter(), req)
     40 +}
     41 + 
  • ■ ■ ■ ■ ■
    pkg/router/proxy/proxy.go
    skipped 18 lines
    19 19   proxy.Any("/grafana/{cluster_name}/{p:path}", GrafanaProxy)
    20 20   proxy.Any("/grafana/{cluster_name}", GrafanaProxy)
    21 21   proxy.Any("/chartmuseum/{cluster_name}/{p:path}", ChartmuseumProxy)
     22 + proxy.Any("/prometheus/{cluster_name}/{p:path}", PrometheusProxy)
    22 23   proxy.Any("/dashboard/{cluster_name}/{p:path}", DashboardProxy)
    23 24   proxy.Any("/registry/{cluster_name}/{p:path}", RegistryProxy)
    24 25   proxy.Any("/kubeapps/{cluster_name}/{p:path}", KubeappsProxy)
    skipped 2 lines
  • ■ ■ ■ ■ ■ ■
    pkg/service/backup_account.go
    skipped 45 lines
    46 46  }
    47 47   
    48 48  func (b backupAccountService) Get(name string) (*dto.BackupAccount, error) {
    49  - var backupAccountDTO dto.BackupAccount
     49 + var (
     50 + backupAccountDTO dto.BackupAccount
     51 + projectResources []model.ProjectResource
     52 + clusterResources []model.ClusterResource
     53 + )
    50 54   mo, err := b.backupAccountRepo.Get(name)
    51 55   if err != nil {
    52 56   return nil, err
    53 57   }
     58 + if err := db.DB.Where("resource_id = ?", mo.ID).Preload("Project").Find(&projectResources).Error; err != nil {
     59 + return nil, err
     60 + }
     61 + if err := db.DB.Where("resource_id = ?", mo.ID).Preload("Cluster").Find(&clusterResources).Error; err != nil {
     62 + return nil, err
     63 + }
     64 + var projects string
     65 + for _, pr := range projectResources {
     66 + projects += (pr.Project.Name + ",")
     67 + }
     68 + var clusters string
     69 + for _, cr := range clusterResources {
     70 + clusters += (cr.Cluster.Name + ",")
     71 + }
     72 + 
    54 73   vars := make(map[string]interface{})
    55 74   if err := json.Unmarshal([]byte(mo.Credential), &vars); err != nil {
    56 75   return nil, err
    skipped 1 lines
    58 77   backupAccountDTO = dto.BackupAccount{
    59 78   CredentialVars: vars,
    60 79   BackupAccount: *mo,
     80 + Projects: projects,
     81 + Clusters: clusters,
    61 82   }
    62 83   return &backupAccountDTO, nil
    63 84  }
    skipped 288 lines
  • ■ ■ ■ ■
    pkg/service/cluster_health.go
    skipped 73 lines
    74 74   }
    75 75   results := dto.ClusterHealth{Level: StatusError}
    76 76   results.Level = StatusError
    77  - if clu.Source == constant.ClusterSourceLocal {
     77 + if clu.Source != constant.ClusterSourceExternal {
    78 78   sshclient, sshResult := checkHostSSHConnected(clu.Cluster)
    79 79   results.Hooks = append(results.Hooks, sshResult)
    80 80   if sshResult.Level == StatusError {
    skipped 469 lines
  • ■ ■ ■ ■ ■ ■
    pkg/service/cluster_import.go
    skipped 29 lines
    30 30   clusterRepo repository.ClusterRepository
    31 31   projectRepository repository.ProjectRepository
    32 32   projectResourceRepository repository.ProjectResourceRepository
     33 + messageService MessageService
    33 34  }
    34 35   
    35 36  func NewClusterImportService() *clusterImportService {
    skipped 1 lines
    37 38   clusterRepo: repository.NewClusterRepository(),
    38 39   projectRepository: repository.NewProjectRepository(),
    39 40   projectResourceRepository: repository.NewProjectResourceRepository(),
     41 + messageService: NewMessageService(),
    40 42   }
    41 43  }
    42 44   
    skipped 113 lines
    156 158   Architecture: node.Architecture,
    157 159   }
    158 160   if err := tx.Create(&host).Error; err != nil {
     161 + _ = c.messageService.SendMessage(constant.System, false, GetContent(constant.ClusterImport, false, err.Error()), cluster.Name, constant.ClusterImport)
    159 162   tx.Rollback()
    160 163   return err
    161 164   }
    skipped 7 lines
    169 172   }
    170 173   if err := tx.Create(&node).Error; err != nil {
    171 174   tx.Rollback()
     175 + _ = c.messageService.SendMessage(constant.System, false, GetContent(constant.ClusterImport, false, err.Error()), cluster.Name, constant.ClusterImport)
    172 176   return err
    173 177   }
    174 178   clusterResource := model.ClusterResource{
    skipped 3 lines
    178 182   }
    179 183   if err := tx.Create(&clusterResource).Error; err != nil {
    180 184   tx.Rollback()
     185 + _ = c.messageService.SendMessage(constant.System, false, GetContent(constant.ClusterImport, false, err.Error()), cluster.Name, constant.ClusterImport)
    181 186   return err
    182 187   }
    183 188   projectResource := model.ProjectResource{
    skipped 3 lines
    187 192   }
    188 193   if err := tx.Create(&projectResource).Error; err != nil {
    189 194   tx.Rollback()
     195 + _ = c.messageService.SendMessage(constant.System, false, GetContent(constant.ClusterImport, false, err.Error()), cluster.Name, constant.ClusterImport)
    190 196   return err
    191 197   }
    192 198   }
    193 199   } else {
    194 200   if err := gatherClusterInfo(&cluster); err != nil {
    195 201   tx.Rollback()
     202 + _ = c.messageService.SendMessage(constant.System, false, GetContent(constant.ClusterImport, false, err.Error()), cluster.Name, constant.ClusterImport)
    196 203   return err
    197 204   }
    198 205   for _, node := range cluster.Nodes {
    199 206   node.ClusterID = cluster.ID
    200 207   if err := tx.Create(&node).Error; err != nil {
    201 208   tx.Rollback()
     209 + _ = c.messageService.SendMessage(constant.System, false, GetContent(constant.ClusterImport, false, err.Error()), cluster.Name, constant.ClusterImport)
    202 210   return fmt.Errorf("can not save node %s", err.Error())
    203 211   }
    204 212   }
    skipped 1 lines
    206 214   
    207 215   if err := tx.Save(&cluster.Spec).Error; err != nil {
    208 216   tx.Rollback()
     217 + _ = c.messageService.SendMessage(constant.System, false, GetContent(constant.ClusterImport, false, err.Error()), cluster.Name, constant.ClusterImport)
    209 218   return fmt.Errorf("can not update spec %s", err.Error())
    210 219   }
    211 220   
    skipped 3 lines
    215 224   )
    216 225   if err := tx.Where("name = ?", cluster.Spec.Version).Order("created_at ASC").First(&manifest).Error; err != nil {
    217 226   tx.Rollback()
     227 + _ = c.messageService.SendMessage(constant.System, false, GetContent(constant.ClusterImport, false, err.Error()), cluster.Name, constant.ClusterImport)
    218 228   return fmt.Errorf("can find manifest version: %s", err.Error())
    219 229   }
    220 230   if err := json.Unmarshal([]byte(manifest.ToolVars), &toolVars); err != nil {
    221 231   tx.Rollback()
     232 + _ = c.messageService.SendMessage(constant.System, false, GetContent(constant.ClusterImport, false, err.Error()), cluster.Name, constant.ClusterImport)
    222 233   return fmt.Errorf("unmarshal manifest.toolvar error %s", err.Error())
    223 234   }
    224 235   for _, tool := range cluster.PrepareTools() {
    skipped 6 lines
    231 242   tool.ClusterID = cluster.ID
    232 243   if err := tx.Create(&tool).Error; err != nil {
    233 244   tx.Rollback()
     245 + _ = c.messageService.SendMessage(constant.System, false, GetContent(constant.ClusterImport, false, err.Error()), cluster.Name, constant.ClusterImport)
    234 246   return fmt.Errorf("can not save tool %s", err.Error())
    235 247   }
    236 248   }
    skipped 2 lines
    239 251   istio.ClusterID = cluster.ID
    240 252   if err := tx.Create(&istio).Error; err != nil {
    241 253   tx.Rollback()
     254 + _ = c.messageService.SendMessage(constant.System, false, GetContent(constant.ClusterImport, false, err.Error()), cluster.Name, constant.ClusterImport)
    242 255   return fmt.Errorf("can not save istio %s", err.Error())
    243 256   }
    244 257   }
    skipped 3 lines
    248 261   ResourceType: constant.ResourceCluster,
    249 262   }); err != nil {
    250 263   tx.Rollback()
     264 + _ = c.messageService.SendMessage(constant.System, false, GetContent(constant.ClusterImport, false, err.Error()), cluster.Name, constant.ClusterImport)
    251 265   return fmt.Errorf("can not create project resource %s", err.Error())
    252 266   }
    253 267   tx.Commit()
     268 + _ = c.messageService.SendMessage(constant.System, true, GetContent(constant.ClusterImport, true, ""), cluster.Name, constant.ClusterImport)
    254 269   
    255 270   hostService := NewHostService()
    256 271   go hostService.SyncList(synchosts)
    skipped 282 lines
  • ■ ■ ■ ■ ■ ■
    pkg/service/cluster_tool.go
    skipped 11 lines
    12 12   "github.com/KubeOperator/KubeOperator/pkg/model"
    13 13   "github.com/KubeOperator/KubeOperator/pkg/repository"
    14 14   "github.com/KubeOperator/KubeOperator/pkg/service/cluster/tools"
     15 + helm2 "github.com/KubeOperator/KubeOperator/pkg/util/helm"
    15 16   kubernetesUtil "github.com/KubeOperator/KubeOperator/pkg/util/kubernetes"
     17 + appv1 "k8s.io/api/apps/v1"
    16 18   v1 "k8s.io/api/core/v1"
    17 19   metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    18 20  )
    skipped 1 lines
    20 22  type ClusterToolService interface {
    21 23   List(clusterName string) ([]dto.ClusterTool, error)
    22 24   GetNodePort(clusterName, toolName, toolVersion, namespace string) (dto.ClusterTool, error)
     25 + SyncStatus(clusterName string) ([]dto.ClusterTool, error)
    23 26   Enable(clusterName string, tool dto.ClusterTool) (dto.ClusterTool, error)
    24 27   Upgrade(clusterName string, tool dto.ClusterTool) (dto.ClusterTool, error)
    25 28   Disable(clusterName string, tool dto.ClusterTool) (dto.ClusterTool, error)
    skipped 57 lines
    83 86   return tool, nil
    84 87   }
    85 88   return tool, fmt.Errorf("can't get nodeport %s(%s) from cluster %s", svcName, namespace, clusterName)
     89 +}
     90 + 
     91 +func (c clusterToolService) SyncStatus(clusterName string) ([]dto.ClusterTool, error) {
     92 + var (
     93 + cluster model.Cluster
     94 + tools []model.ClusterTool
     95 + backTools []dto.ClusterTool
     96 + )
     97 + if err := db.DB.Where("name = ?", clusterName).Preload("Spec").Preload("Secret").Find(&cluster).Error; err != nil {
     98 + return backTools, err
     99 + }
     100 + if err := db.DB.Where("cluster_id = ?", cluster.ID).Find(&tools).Error; err != nil {
     101 + return backTools, err
     102 + }
     103 + kubeClient, err := kubernetesUtil.NewKubernetesClient(&kubernetesUtil.Config{
     104 + Hosts: []kubernetesUtil.Host{kubernetesUtil.Host(fmt.Sprintf("%s:%d", cluster.Spec.KubeRouter, cluster.Spec.KubeApiServerPort))},
     105 + Token: cluster.Secret.KubernetesToken,
     106 + })
     107 + if err != nil {
     108 + return backTools, err
     109 + }
     110 + var (
     111 + allDeployments []appv1.Deployment
     112 + allStatefulsets []appv1.StatefulSet
     113 + )
     114 + namespaceList, err := kubeClient.CoreV1().Namespaces().List(context.Background(), metav1.ListOptions{})
     115 + if err != nil {
     116 + return backTools, err
     117 + }
     118 + for _, ns := range namespaceList.Items {
     119 + deployments, err := kubeClient.AppsV1().Deployments(ns.Name).List(context.TODO(), metav1.ListOptions{})
     120 + if err != nil {
     121 + return backTools, err
     122 + }
     123 + allDeployments = append(allDeployments, deployments.Items...)
     124 + statefulsets, err := kubeClient.AppsV1().StatefulSets(ns.Name).List(context.TODO(), metav1.ListOptions{})
     125 + if err != nil {
     126 + return backTools, err
     127 + }
     128 + allStatefulsets = append(allStatefulsets, statefulsets.Items...)
     129 + }
     130 + for _, tool := range tools {
     131 + dtoItem := dto.ClusterTool{
     132 + ClusterTool: tool,
     133 + Vars: map[string]interface{}{},
     134 + }
     135 + isEnable := false
     136 + sourceName := ""
     137 + sourceType := "deployment"
     138 + switch tool.Name {
     139 + case "registry":
     140 + sourceName = constant.DefaultRegistryDeploymentName
     141 + case "chartmuseum":
     142 + sourceName = constant.DefaultChartmuseumDeploymentName
     143 + case "kubepi":
     144 + sourceName = constant.DefaultKubePiDeploymentName
     145 + case "kubeapps":
     146 + sourceName = constant.DefaultKubeappsDeploymentName
     147 + case "grafana":
     148 + sourceName = constant.DefaultGrafanaDeploymentName
     149 + case "prometheus":
     150 + sourceName = constant.DefaultPrometheusDeploymentName
     151 + case "logging":
     152 + sourceName = constant.DefaultLoggingStateSetsfulName
     153 + sourceType = "statefulset"
     154 + case "loki":
     155 + sourceName = constant.DefaultLokiStateSetsfulName
     156 + sourceType = "statefulset"
     157 + }
     158 + if sourceType == "deployment" {
     159 + for _, deploy := range allDeployments {
     160 + if deploy.ObjectMeta.Name == sourceName {
     161 + if deploy.Status.ReadyReplicas > 0 {
     162 + isEnable = true
     163 + tool.Status = constant.StatusRunning
     164 + } else {
     165 + tool.Status = constant.StatusWaiting
     166 + }
     167 + dtoItem.Vars["namespace"] = deploy.ObjectMeta.Namespace
     168 + buf, _ := json.Marshal(&dtoItem.Vars)
     169 + tool.Vars = string(buf)
     170 + _ = db.DB.Model(&model.ClusterTool{}).Updates(&tool)
     171 + break
     172 + }
     173 + }
     174 + }
     175 + if sourceType == "statefulset" {
     176 + for _, statefulset := range allStatefulsets {
     177 + if statefulset.ObjectMeta.Name == sourceName {
     178 + if statefulset.Status.ReadyReplicas > 0 {
     179 + isEnable = true
     180 + tool.Status = constant.StatusRunning
     181 + } else {
     182 + tool.Status = constant.StatusWaiting
     183 + }
     184 + dtoItem.Vars["namespace"] = statefulset.ObjectMeta.Namespace
     185 + buf, _ := json.Marshal(&dtoItem.Vars)
     186 + tool.Vars = string(buf)
     187 + _ = db.DB.Model(&model.ClusterTool{}).Updates(&tool)
     188 + break
     189 + }
     190 + }
     191 + }
     192 + if !isEnable {
     193 + if tool.Status != constant.StatusWaiting {
     194 + tool.Status = constant.StatusWaiting
     195 + _ = db.DB.Model(&model.ClusterTool{}).Updates(&tool)
     196 + }
     197 + }
     198 + dtoItem.ClusterTool = tool
     199 + backTools = append(backTools, dtoItem)
     200 + }
     201 + 
     202 + var h helm2.Client
     203 + err = h.SyncRepoCharts(cluster.Spec.Architectures)
     204 + return backTools, err
    86 205  }
    87 206   
    88 207  func (c clusterToolService) Disable(clusterName string, tool dto.ClusterTool) (dto.ClusterTool, error) {
    skipped 189 lines
  • ■ ■ ■ ■
    pkg/service/cluster_upgrade.go
    skipped 46 lines
    47 47   if err != nil {
    48 48   return fmt.Errorf("can not get cluster %s error %s", upgrade.ClusterName, err.Error())
    49 49   }
    50  - if !(cluster.Source == constant.ClusterSourceLocal) {
     50 + if cluster.Source == constant.ClusterSourceExternal {
    51 51   return errors.New("CLUSTER_IS_NOT_LOCAL")
    52 52   }
    53 53   if cluster.Status != constant.StatusRunning && cluster.Status != constant.StatusFailed {
    skipped 141 lines
  • ■ ■ ■ ■ ■ ■
    pkg/service/system_setting.go
    skipped 34 lines
    35 35   UpdateRegistry(arch string, creation dto.SystemRegistryUpdate) (*dto.SystemRegistry, error)
    36 36   BatchRegistry(op dto.SystemRegistryBatchOp) error
    37 37   DeleteRegistry(id string) error
     38 + ChangePassword(repo dto.RepoChangePassword) error
    38 39  }
    39 40   
    40 41  type systemSettingService struct {
    skipped 244 lines
    285 286   RegistryHostedPort: creation.RegistryHostedPort,
    286 287   NexusPassword: creation.NexusPassword,
    287 288   }
    288  - err := s.systemRegistryRepo.Save(&systemRegistry)
    289  - if err != nil {
     289 + if err := s.systemRegistryRepo.Save(&systemRegistry); err != nil {
    290 290   return nil, err
    291 291   }
    292 292   return &dto.SystemRegistry{SystemRegistry: systemRegistry}, nil
    skipped 23 lines
    316 316   return nil
    317 317  }
    318 318   
     319 +func (u *systemSettingService) ChangePassword(ch dto.RepoChangePassword) error {
     320 + repo, err := u.GetRegistryByID(ch.ID)
     321 + if err != nil {
     322 + return err
     323 + }
     324 + success, err := validateOldPassword(repo, ch.Original)
     325 + if err != nil {
     326 + return err
     327 + }
     328 + if !success {
     329 + return errOriginalNotMatch
     330 + }
     331 + repo.NexusPassword, err = encrypt.StringEncrypt(ch.Password)
     332 + if err != nil {
     333 + return err
     334 + }
     335 + if err := db.DB.Model(&model.SystemRegistry{}).Where("id = ?", repo.ID).Update(map[string]interface{}{"nexus_password": repo.NexusPassword}).Error; err != nil {
     336 + return err
     337 + }
     338 + return err
     339 +}
     340 + 
     341 +func validateOldPassword(repo dto.SystemRegistry, password string) (bool, error) {
     342 + oldPassword, err := encrypt.StringDecrypt(repo.NexusPassword)
     343 + if err != nil {
     344 + return false, err
     345 + }
     346 + if oldPassword != password {
     347 + return false, err
     348 + }
     349 + return true, err
     350 +}
     351 + 
  • ■ ■ ■ ■ ■ ■
    pkg/util/helm/helm.go
    skipped 42 lines
    43 43   Uninstall(name string) (*release.UninstallReleaseResponse, error)
    44 44   List() ([]*release.Release, error)
    45 45   GetRepoIP(arch string) (string, string, int, int, error)
     46 + SyncRepoCharts(arch string) error
    46 47  }
    47 48   
    48 49  type Config struct {
    skipped 127 lines
    176 177   
    177 178  }
    178 179   
     180 +// 每次启用或升级的时候执行,存在 nexus 则不采取操作
    179 181  func updateRepo(arch string) error {
    180 182   repos, err := ListRepo()
    181 183   if err != nil {
    skipped 7 lines
    189 191   }
    190 192   }
    191 193   if !flag {
    192  - r := repository.NewSystemSettingRepository()
    193  - p, err := r.Get("REGISTRY_PROTOCOL")
    194  - if err != nil {
    195  - return fmt.Errorf("load system repo failed: %v", err)
     194 + if err := addRepo(arch); err != nil {
     195 + return err
    196 196   }
    197  - var c Client
    198  - repoIP, nexusPsw, repoPort, _, err := c.GetRepoIP(arch)
    199  - if err != nil {
    200  - return fmt.Errorf("load system repo of arch %s failed: %v", arch, err)
    201  - }
    202  - url := fmt.Sprintf("%s://%s:%d/repository/applications", p.Value, repoIP, repoPort)
    203  - err = addRepo("nexus", url, "admin", nexusPsw)
    204  - if err != nil {
    205  - return fmt.Errorf("add helm repo %s failed: %v", url, err)
    206  - }
    207  - logger.Log.Infof("my nexus addr is %s", url)
    208  - }
    209  - settings := GetSettings()
    210  - repoFile := settings.RepositoryConfig
    211  - repoCache := settings.RepositoryCache
    212  - f, err := repo.LoadFile(repoFile)
    213  - if err != nil {
    214  - return fmt.Errorf("load file of repo %s failed: %v", repoFile, err)
    215  - }
    216  - var rps []*repo.ChartRepository
    217  - for _, cfg := range f.Repositories {
    218  - r, err := repo.NewChartRepository(cfg, getter.All(settings))
    219  - if err != nil {
     197 + if err := updateCharts(); err != nil {
    220 198   return err
    221 199   }
    222  - if repoCache != "" {
    223  - r.CachePath = repoCache
    224  - }
    225  - rps = append(rps, r)
    226 200   }
    227  - updateCharts(rps)
    228 201   return nil
    229 202  }
    230 203   
    231  -func updateCharts(repos []*repo.ChartRepository) {
    232  - logger.Log.Debug("Hang tight while we grab the latest from your chart repositories...")
    233  - var wg sync.WaitGroup
    234  - for _, re := range repos {
    235  - wg.Add(1)
    236  - go func(re *repo.ChartRepository) {
    237  - defer wg.Done()
    238  - if _, err := re.DownloadIndexFile(); err != nil {
    239  - logger.Log.Debugf("...Unable to get an update from the %q chart repository (%s):\n\t%s\n", re.Config.Name, re.Config.URL, err)
    240  - } else {
    241  - logger.Log.Debugf("...Successfully got an update from the %q chart repository\n", re.Config.Name)
    242  - }
    243  - }(re)
     204 +func (c Client) SyncRepoCharts(arch string) error {
     205 + if err := addRepo(arch); err != nil {
     206 + return err
    244 207   }
    245  - wg.Wait()
    246  - logger.Log.Debugf("Update Complete. ⎈ Happy Helming!⎈ ")
     208 + if err := updateCharts(); err != nil {
     209 + return err
     210 + }
     211 + return nil
    247 212  }
    248 213   
    249  -func addRepo(name string, url string, username string, password string) error {
     214 +func addRepo(arch string) error {
     215 + username := "admin"
     216 + name := "nexus"
     217 + repository := repository.NewSystemSettingRepository()
     218 + p, err := repository.Get("REGISTRY_PROTOCOL")
     219 + if err != nil {
     220 + return fmt.Errorf("load system repo failed: %v", err)
     221 + }
     222 + var c Client
     223 + repoIP, password, repoPort, _, err := c.GetRepoIP(arch)
     224 + if err != nil {
     225 + return fmt.Errorf("load system repo of arch %s failed: %v", arch, err)
     226 + }
     227 + url := fmt.Sprintf("%s://%s:%d/repository/applications", p.Value, repoIP, repoPort)
     228 + logger.Log.Infof("my helm repo url is %s", url)
     229 + 
    250 230   settings := GetSettings()
    251 231   
    252 232   repoFile := settings.RepositoryConfig
    253 233   
    254  - err := os.MkdirAll(filepath.Dir(repoFile), os.ModePerm)
    255  - if err != nil && !os.IsExist(err) {
     234 + if err := os.MkdirAll(filepath.Dir(repoFile), os.ModePerm); err != nil && !os.IsExist(err) {
    256 235   return err
    257 236   }
    258 237   
    skipped 20 lines
    279 258   var f repo.File
    280 259   if err := yaml.Unmarshal(b, &f); err != nil {
    281 260   return err
    282  - }
    283  - 
    284  - if f.Has(name) {
    285  - return errors.Errorf("repository name (%s) already exists, please specify a different name", name)
    286 261   }
    287 262   
    288 263   e := repo.Entry{
    skipped 21 lines
    310 285   return nil
    311 286  }
    312 287   
     288 +func updateCharts() error {
     289 + logger.Log.Debug("Hang tight while we grab the latest from your chart repositories...")
     290 + settings := GetSettings()
     291 + repoFile := settings.RepositoryConfig
     292 + repoCache := settings.RepositoryCache
     293 + f, err := repo.LoadFile(repoFile)
     294 + if err != nil {
     295 + return fmt.Errorf("load file of repo %s failed: %v", repoFile, err)
     296 + }
     297 + var rps []*repo.ChartRepository
     298 + for _, cfg := range f.Repositories {
     299 + r, err := repo.NewChartRepository(cfg, getter.All(settings))
     300 + if err != nil {
     301 + return fmt.Errorf("get new chart repository failed, err: %v", err.Error())
     302 + }
     303 + if repoCache != "" {
     304 + r.CachePath = repoCache
     305 + }
     306 + rps = append(rps, r)
     307 + }
     308 + 
     309 + var wg sync.WaitGroup
     310 + for _, re := range rps {
     311 + wg.Add(1)
     312 + go func(re *repo.ChartRepository) {
     313 + defer wg.Done()
     314 + if _, err := re.DownloadIndexFile(); err != nil {
     315 + logger.Log.Debugf("...Unable to get an update from the %q chart repository (%s):\n\t%s\n", re.Config.Name, re.Config.URL, err)
     316 + } else {
     317 + logger.Log.Debugf("...Successfully got an update from the %q chart repository\n", re.Config.Name)
     318 + }
     319 + }(re)
     320 + }
     321 + wg.Wait()
     322 + logger.Log.Debugf("Update Complete. ⎈ Happy Helming!⎈ ")
     323 + return nil
     324 +}
     325 + 
    313 326  func (c Client) GetRepoIP(arch string) (string, string, int, int, error) {
    314 327   var repo model.SystemRegistry
    315 328   switch arch {
    skipped 6 lines
    322 335   return repo.Hostname, repo.NexusPassword, repo.RepoPort, repo.RegistryPort, fmt.Errorf("decrypt password %s failed, err: %v", p, err)
    323 336   }
    324 337   return repo.Hostname, p, repo.RepoPort, repo.RegistryPort, nil
    325  - case "arm64":
    326  - if err := db.DB.Where("architecture = ?", constant.ArchitectureOfARM64).First(&repo).Error; err != nil {
    327  - return "", "", 0, 0, err
    328  - }
    329  - p, err := encrypt.StringDecrypt(repo.NexusPassword)
    330  - if err != nil {
    331  - return repo.Hostname, repo.NexusPassword, repo.RepoPort, repo.RegistryPort, fmt.Errorf("decrypt password %s failed, err: %v", p, err)
    332  - }
    333  - return repo.Hostname, p, repo.RepoPort, repo.RegistryPort, nil
    334  - case "all":
     338 + case "arm64", "all":
    335 339   if err := db.DB.Where("architecture = ?", constant.ArchitectureOfARM64).First(&repo).Error; err != nil {
    336 340   return "", "", 0, 0, err
    337 341   }
    skipped 19 lines
Please wait...
Page is in error, reload to recover