github.com/oam-dev/kubevela@v1.9.11/references/cli/top/model/cluster_namespace.go (about)

     1  /*
     2  Copyright 2022 The KubeVela Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8  	http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package model
    18  
    19  import (
    20  	"context"
    21  	"time"
    22  
    23  	v1 "k8s.io/api/core/v1"
    24  	"k8s.io/apimachinery/pkg/types"
    25  	"sigs.k8s.io/controller-runtime/pkg/client"
    26  
    27  	"github.com/oam-dev/kubevela/references/cli/top/utils"
    28  )
    29  
    30  // ListClusterNamespaces return namespace of application's resource
    31  func ListClusterNamespaces(ctx context.Context, c client.Client) (NamespaceList, error) {
    32  	name := ctx.Value(&CtxKeyAppName).(string)
    33  	ns := ctx.Value(&CtxKeyNamespace).(string)
    34  	app, err := LoadApplication(c, name, ns)
    35  	if err != nil {
    36  		return NamespaceList{}, err
    37  	}
    38  	clusterNSSet := make(map[string]interface{})
    39  	for _, svc := range app.Status.AppliedResources {
    40  		if svc.Namespace != "" {
    41  			clusterNSSet[svc.Namespace] = struct{}{}
    42  		}
    43  	}
    44  	nsList := make(NamespaceList, len(clusterNSSet))
    45  	index := 0
    46  	for clusterNS := range clusterNSSet {
    47  		namespaceInfo, err := LoadNamespaceDetail(ctx, c, clusterNS)
    48  		if err != nil {
    49  			continue
    50  		}
    51  		nsList[index] = Namespace{
    52  			name:   namespaceInfo.Name,
    53  			status: string(namespaceInfo.Status.Phase),
    54  			age:    utils.TimeFormat(time.Since(namespaceInfo.CreationTimestamp.Time)),
    55  		}
    56  		index++
    57  	}
    58  
    59  	return nsList, nil
    60  }
    61  
    62  // LoadNamespaceDetail query detail info of a namespace by name
    63  func LoadNamespaceDetail(ctx context.Context, c client.Client, namespace string) (*v1.Namespace, error) {
    64  	ns := new(v1.Namespace)
    65  	if err := c.Get(ctx, types.NamespacedName{Name: namespace}, ns); err != nil {
    66  		return nil, err
    67  	}
    68  	return ns, nil
    69  }