applications.go 12.0 KB
Newer Older
Z
zryfish 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*

 Copyright 2019 The KubeSphere Authors.

 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.

*/
H
hongming 已提交
18
package openpitrix
Z
zryfish 已提交
19 20

import (
H
hongming 已提交
21
	"fmt"
H
hongming 已提交
22 23 24
	"github.com/golang/protobuf/ptypes/wrappers"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
H
hongming 已提交
25
	appsv1 "k8s.io/api/apps/v1"
Z
zryfish 已提交
26 27 28 29 30
	"k8s.io/api/core/v1"
	"k8s.io/api/extensions/v1beta1"
	"k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/labels"
J
Jeff 已提交
31
	"k8s.io/klog"
H
hongming 已提交
32
	"kubesphere.io/kubesphere/pkg/constants"
Z
zryfish 已提交
33 34 35
	"kubesphere.io/kubesphere/pkg/informers"
	"kubesphere.io/kubesphere/pkg/models"
	"kubesphere.io/kubesphere/pkg/models/resources"
J
Jeff 已提交
36
	"kubesphere.io/kubesphere/pkg/server/params"
H
hongming 已提交
37
	cs "kubesphere.io/kubesphere/pkg/simple/client"
H
hongming 已提交
38
	"kubesphere.io/kubesphere/pkg/simple/client/openpitrix"
H
hongming 已提交
39
	"openpitrix.io/openpitrix/pkg/pb"
Z
zryfish 已提交
40 41 42 43
	"strings"
)

type Application struct {
H
hongming 已提交
44 45 46 47 48 49 50
	Name      string            `json:"name" description:"application name"`
	Cluster   *Cluster          `json:"cluster,omitempty" description:"application cluster info"`
	Version   *AppVersion       `json:"version,omitempty" description:"application template version info"`
	App       *App              `json:"app,omitempty" description:"application template info"`
	WorkLoads *workLoads        `json:"workloads,omitempty" description:"application workloads"`
	Services  []v1.Service      `json:"services,omitempty" description:"application services"`
	Ingresses []v1beta1.Ingress `json:"ingresses,omitempty" description:"application ingresses"`
Z
zryfish 已提交
51 52 53
}

type workLoads struct {
H
hongming 已提交
54 55 56
	Deployments  []appsv1.Deployment  `json:"deployments,omitempty" description:"deployment list"`
	Statefulsets []appsv1.StatefulSet `json:"statefulsets,omitempty" description:"statefulset list"`
	Daemonsets   []appsv1.DaemonSet   `json:"daemonsets,omitempty" description:"daemonset list"`
Z
zryfish 已提交
57 58
}

H
hongming 已提交
59
func ListApplications(conditions *params.Conditions, limit, offset int, orderBy string, reverse bool) (*models.PageableResponse, error) {
H
hongming 已提交
60
	client, err := cs.ClientSets().OpenPitrix()
61
	if err != nil {
H
hongming 已提交
62
		klog.Error(err)
63 64
		return nil, err
	}
H
hongming 已提交
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
	describeClustersRequest := &pb.DescribeClustersRequest{
		Limit:  uint32(limit),
		Offset: uint32(offset)}
	if keyword := conditions.Match["keyword"]; keyword != "" {
		describeClustersRequest.SearchWord = &wrappers.StringValue{Value: keyword}
	}
	if runtimeId := conditions.Match["runtime_id"]; runtimeId != "" {
		describeClustersRequest.RuntimeId = []string{runtimeId}
	}
	if appId := conditions.Match["app_id"]; appId != "" {
		describeClustersRequest.AppId = []string{appId}
	}
	if versionId := conditions.Match["version_id"]; versionId != "" {
		describeClustersRequest.VersionId = []string{versionId}
	}
	if status := conditions.Match["status"]; status != "" {
		describeClustersRequest.Status = strings.Split(status, "|")
	}
H
hongming 已提交
83 84 85
	if orderBy != "" {
		describeClustersRequest.SortKey = &wrappers.StringValue{Value: orderBy}
	}
H
hongming 已提交
86
	describeClustersRequest.Reverse = &wrappers.BoolValue{Value: !reverse}
H
hongming 已提交
87
	resp, err := client.Cluster().DescribeClusters(openpitrix.SystemContext(), describeClustersRequest)
Z
zryfish 已提交
88
	if err != nil {
H
hongming 已提交
89
		klog.Errorln(err)
H
hongming 已提交
90
		return nil, err
Z
zryfish 已提交
91
	}
H
hongming 已提交
92
	result := models.PageableResponse{TotalCount: int(resp.TotalCount)}
H
hongming 已提交
93
	result.Items = make([]interface{}, 0)
H
hongming 已提交
94 95 96 97 98 99
	for _, cluster := range resp.ClusterSet {
		app, err := describeApplication(cluster)
		if err != nil {
			klog.Errorln(err)
			return nil, err
		}
H
hongming 已提交
100
		result.Items = append(result.Items, app)
Z
zryfish 已提交
101 102
	}

H
hongming 已提交
103
	return &result, nil
Z
zryfish 已提交
104 105
}

H
hongming 已提交
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
func describeApplication(cluster *pb.Cluster) (*Application, error) {
	op, err := cs.ClientSets().OpenPitrix()
	if err != nil {
		klog.Error(err)
		return nil, err
	}
	var app Application
	app.Name = cluster.Name.Value
	app.Cluster = convertCluster(cluster)
	versionInfo, err := op.App().DescribeAppVersions(openpitrix.SystemContext(), &pb.DescribeAppVersionsRequest{VersionId: []string{cluster.GetVersionId().GetValue()}})
	if err != nil {
		klog.Errorln(err)
		return nil, err
	}
	if len(versionInfo.AppVersionSet) > 0 {
		app.Version = convertAppVersion(versionInfo.AppVersionSet[0])
	}
	appInfo, err := op.App().DescribeApps(openpitrix.SystemContext(), &pb.DescribeAppsRequest{AppId: []string{cluster.GetAppId().GetValue()}, Limit: 1})
124
	if err != nil {
H
hongming 已提交
125
		klog.Errorln(err)
126 127
		return nil, err
	}
H
hongming 已提交
128 129 130 131 132 133 134
	if len(appInfo.AppSet) > 0 {
		app.App = convertApp(appInfo.GetAppSet()[0])
	}
	return &app, nil
}

func DescribeApplication(namespace string, clusterId string) (*Application, error) {
Z
zryfish 已提交
135

H
hongming 已提交
136
	client, err := cs.ClientSets().OpenPitrix()
Z
zryfish 已提交
137
	if err != nil {
J
Jeff 已提交
138
		klog.Error(err)
H
hongming 已提交
139
		return nil, err
Z
zryfish 已提交
140 141
	}

H
hongming 已提交
142
	clusters, err := client.Cluster().DescribeClusters(openpitrix.SystemContext(), &pb.DescribeClustersRequest{ClusterId: []string{clusterId}, Limit: 1})
Z
zryfish 已提交
143 144

	if err != nil {
H
hongming 已提交
145
		klog.Errorln(err)
H
hongming 已提交
146
		return nil, err
Z
zryfish 已提交
147 148
	}

H
hongming 已提交
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
	var cluster *pb.Cluster
	if len(clusters.ClusterSet) > 0 {
		cluster = clusters.GetClusterSet()[0]
	} else {
		err := status.New(codes.NotFound, "resource not found").Err()
		klog.Errorln(err)
		return nil, err
	}
	app, err := describeApplication(cluster)
	if err != nil {
		klog.Errorln(err)
		return nil, err
	}

	workloads, err := getWorkLoads(namespace, cluster.ClusterRoleSet)

	if err != nil {
		klog.Errorln(err)
		return nil, err
	}
	app.WorkLoads = workloads
	workloadLabels := getLabels(namespace, app.WorkLoads)
	app.Services = getSvcs(namespace, workloadLabels)
	app.Ingresses = getIng(namespace, app.Services)
	return app, nil
Z
zryfish 已提交
174 175
}

H
hongming 已提交
176
func getWorkLoads(namespace string, clusterRoles []*pb.ClusterRole) (*workLoads, error) {
Z
zryfish 已提交
177 178 179

	var works workLoads
	for _, clusterRole := range clusterRoles {
H
hongming 已提交
180
		workLoadName := clusterRole.Role.Value
Z
zryfish 已提交
181
		if len(workLoadName) > 0 {
H
hongming 已提交
182 183
			if strings.HasSuffix(workLoadName, openpitrix.DeploySuffix) {
				name := strings.Split(workLoadName, openpitrix.DeploySuffix)[0]
Z
zryfish 已提交
184 185 186 187

				item, err := informers.SharedInformerFactory().Apps().V1().Deployments().Lister().Deployments(namespace).Get(name)

				if err != nil {
188 189 190 191
					// app not ready
					if errors.IsNotFound(err) {
						continue
					}
H
hongming 已提交
192
					klog.Errorln(err)
Z
zryfish 已提交
193 194 195 196 197 198 199
					return nil, err
				}

				works.Deployments = append(works.Deployments, *item)
				continue
			}

H
hongming 已提交
200 201
			if strings.HasSuffix(workLoadName, openpitrix.DaemonSuffix) {
				name := strings.Split(workLoadName, openpitrix.DaemonSuffix)[0]
Z
zryfish 已提交
202 203
				item, err := informers.SharedInformerFactory().Apps().V1().DaemonSets().Lister().DaemonSets(namespace).Get(name)
				if err != nil {
204 205 206 207
					// app not ready
					if errors.IsNotFound(err) {
						continue
					}
H
hongming 已提交
208
					klog.Errorln(err)
Z
zryfish 已提交
209 210 211 212 213 214
					return nil, err
				}
				works.Daemonsets = append(works.Daemonsets, *item)
				continue
			}

H
hongming 已提交
215 216
			if strings.HasSuffix(workLoadName, openpitrix.StateSuffix) {
				name := strings.Split(workLoadName, openpitrix.StateSuffix)[0]
Z
zryfish 已提交
217 218
				item, err := informers.SharedInformerFactory().Apps().V1().StatefulSets().Lister().StatefulSets(namespace).Get(name)
				if err != nil {
219 220 221 222
					// app not ready
					if errors.IsNotFound(err) {
						continue
					}
H
hongming 已提交
223
					klog.Errorln(err)
Z
zryfish 已提交
224 225 226 227 228 229 230 231 232 233 234
					return nil, err
				}
				works.Statefulsets = append(works.Statefulsets, *item)
				continue
			}
		}
	}
	return &works, nil
}

func getLabels(namespace string, workloads *workLoads) *[]map[string]string {
H
hongming 已提交
235
	k8sClient := cs.ClientSets().K8s().Kubernetes()
Z
zryfish 已提交
236

H
hongming 已提交
237
	var workloadLabels []map[string]string
Z
zryfish 已提交
238 239 240 241 242 243 244 245 246
	if workloads == nil {
		return nil
	}

	for _, workload := range workloads.Deployments {
		deploy, err := k8sClient.AppsV1().Deployments(namespace).Get(workload.Name, metav1.GetOptions{})
		if errors.IsNotFound(err) {
			continue
		}
H
hongming 已提交
247
		workloadLabels = append(workloadLabels, deploy.Labels)
Z
zryfish 已提交
248 249 250 251 252 253 254
	}

	for _, workload := range workloads.Daemonsets {
		daemonset, err := k8sClient.AppsV1().DaemonSets(namespace).Get(workload.Name, metav1.GetOptions{})
		if errors.IsNotFound(err) {
			continue
		}
H
hongming 已提交
255
		workloadLabels = append(workloadLabels, daemonset.Labels)
Z
zryfish 已提交
256 257 258 259 260 261 262
	}

	for _, workload := range workloads.Statefulsets {
		statefulset, err := k8sClient.AppsV1().StatefulSets(namespace).Get(workload.Name, metav1.GetOptions{})
		if errors.IsNotFound(err) {
			continue
		}
H
hongming 已提交
263
		workloadLabels = append(workloadLabels, statefulset.Labels)
Z
zryfish 已提交
264 265
	}

H
hongming 已提交
266
	return &workloadLabels
Z
zryfish 已提交
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
}

func isExist(svcs []v1.Service, svc v1.Service) bool {
	for _, item := range svcs {
		if item.Name == svc.Name && item.Namespace == svc.Namespace {
			return true
		}
	}
	return false
}

func getSvcs(namespace string, workLoadLabels *[]map[string]string) []v1.Service {
	if len(*workLoadLabels) == 0 {
		return nil
	}
H
hongming 已提交
282
	k8sClient := cs.ClientSets().K8s().Kubernetes()
Z
zryfish 已提交
283 284 285 286 287
	var services []v1.Service
	for _, label := range *workLoadLabels {
		labelSelector := labels.Set(label).AsSelector().String()
		svcs, err := k8sClient.CoreV1().Services(namespace).List(metav1.ListOptions{LabelSelector: labelSelector})
		if err != nil {
J
Jeff 已提交
288
			klog.Errorf("get app's svc failed, reason: %v", err)
Z
zryfish 已提交
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
		}
		for _, item := range svcs.Items {
			if !isExist(services, item) {
				services = append(services, item)
			}
		}
	}

	return services
}

func getIng(namespace string, services []v1.Service) []v1beta1.Ingress {
	if services == nil {
		return nil
	}

	var ings []v1beta1.Ingress
	for _, svc := range services {
H
hongming 已提交
307
		result, err := resources.ListResources(namespace, "ingress", &params.Conditions{Fuzzy: map[string]string{"serviceName": svc.Name}}, "", false, -1, 0)
Z
zryfish 已提交
308
		if err != nil {
H
hongming 已提交
309
			klog.Errorln(err)
Z
zryfish 已提交
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
			return nil
		}

		for _, i := range result.Items {
			ingress := i.(*v1beta1.Ingress)

			exist := false
			var tmpRules []v1beta1.IngressRule
			for _, rule := range ingress.Spec.Rules {
				for _, p := range rule.HTTP.Paths {
					if p.Backend.ServiceName == svc.Name {
						exist = true
						tmpRules = append(tmpRules, rule)
					}
				}

			}

			if exist {
				ing := v1beta1.Ingress{}
				ing.Name = ingress.Name
				ing.Spec.Rules = tmpRules
				ings = append(ings, ing)
			}
		}
	}

	return ings
}
H
hongming 已提交
339

H
hongming 已提交
340
func CreateApplication(namespace string, request CreateClusterRequest) error {
H
hongming 已提交
341 342
	ns, err := informers.SharedInformerFactory().Core().V1().Namespaces().Lister().Get(namespace)
	if err != nil {
H
hongming 已提交
343
		klog.Error(err)
H
hongming 已提交
344 345 346 347
		return err
	}

	if runtimeId := ns.Annotations[constants.OpenPitrixRuntimeAnnotationKey]; runtimeId != "" {
H
hongming 已提交
348
		request.RuntimeId = runtimeId
H
hongming 已提交
349 350 351
	} else {
		return fmt.Errorf("runtime not init: namespace %s", namespace)
	}
H
hongming 已提交
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397

	client, err := cs.ClientSets().OpenPitrix()

	if err != nil {
		klog.Error(err)
		return err
	}

	_, err = client.Cluster().CreateCluster(openpitrix.ContextWithUsername(request.Username), &pb.CreateClusterRequest{
		AppId:     &wrappers.StringValue{Value: request.AppId},
		VersionId: &wrappers.StringValue{Value: request.VersionId},
		RuntimeId: &wrappers.StringValue{Value: request.RuntimeId},
		Conf:      &wrappers.StringValue{Value: request.Conf},
	})

	if err != nil {
		klog.Errorln(err)
		return err
	}

	return nil
}

func PatchApplication(request *ModifyClusterAttributesRequest) error {
	op, err := cs.ClientSets().OpenPitrix()

	if err != nil {
		klog.Error(err)
		return err
	}

	modifyClusterAttributesRequest := &pb.ModifyClusterAttributesRequest{ClusterId: &wrappers.StringValue{Value: request.ClusterID}}
	if request.Name != nil {
		modifyClusterAttributesRequest.Name = &wrappers.StringValue{Value: *request.Name}
	}
	if request.Description != nil {
		modifyClusterAttributesRequest.Description = &wrappers.StringValue{Value: *request.Description}
	}

	_, err = op.Cluster().ModifyClusterAttributes(openpitrix.SystemContext(), modifyClusterAttributesRequest)

	if err != nil {
		klog.Errorln(err)
		return err
	}
	return nil
H
hongming 已提交
398 399 400
}

func DeleteApplication(clusterId string) error {
H
hongming 已提交
401 402 403 404 405 406 407 408 409
	client, err := cs.ClientSets().OpenPitrix()

	if err != nil {
		klog.Error(err)
		return err
	}

	_, err = client.Cluster().DeleteClusters(openpitrix.SystemContext(), &pb.DeleteClustersRequest{ClusterId: []string{clusterId}, Force: &wrappers.BoolValue{Value: true}})

410
	if err != nil {
H
hongming 已提交
411
		klog.Errorln(err)
412 413 414
		return err
	}

H
hongming 已提交
415
	return nil
H
hongming 已提交
416
}