access k8s
[msb/service-mesh.git] / msb2pilot / src / msb2pilot / pilot / controller.go
1 /**
2  * Copyright (c) 2018 ZTE Corporation.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * and the Apache License 2.0 which both accompany this distribution,
6  * and are available at http://www.eclipse.org/legal/epl-v10.html
7  * and http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Contributors:
10  *     ZTE - initial Project
11  */
12 package pilot
13
14 import (
15         "errors"
16         "msb2pilot/log"
17
18         "istio.io/istio/pilot/pkg/config/kube/crd"
19         "istio.io/istio/pilot/pkg/model"
20 )
21
22 type Operation string
23
24 var (
25         client *crd.Client
26 )
27
28 func init() {
29         var err error
30         client, err = crd.NewClient("k8s.yml", model.ConfigDescriptor{
31                 model.RouteRule,
32                 model.DestinationPolicy,
33                 model.DestinationRule,
34         }, "")
35
36         if err != nil {
37                 log.Log.Error("fail to init crd", err)
38         }
39 }
40
41 func Get(typ, namespace, name string) (*model.Config, bool) {
42         proto, err := protoSchema(typ)
43         if err != nil {
44                 log.Log.Informational("get resource error", err)
45                 return &model.Config{}, false
46         }
47         return client.Get(proto.Type, name, namespace)
48 }
49
50 func protoSchema(typ string) (model.ProtoSchema, error) {
51         for _, desc := range client.ConfigDescriptor() {
52                 switch typ {
53                 case crd.ResourceName(desc.Type), crd.ResourceName(desc.Plural):
54                         return desc, nil
55                 }
56         }
57         return model.ProtoSchema{}, errors.New("can not find this kind of resources:[" + typ + "]")
58 }
59
60 func List(typ, namespace string) ([]model.Config, error) {
61         proto, err := protoSchema(typ)
62         if err != nil {
63                 return nil, err
64         }
65         return client.List(proto.Type, namespace)
66 }