main.go 7.3 KB
Newer Older
J
jeff 已提交
1
/*
H
hongming 已提交
2
Copyright 2019 The KubeSphere Authors.
J
jeff 已提交
3

H
hongming 已提交
4 5 6
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
J
jeff 已提交
7

H
hongming 已提交
8
    http://www.apache.org/licenses/LICENSE-2.0
J
jeff 已提交
9

H
hongming 已提交
10 11 12 13 14
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.
J
jeff 已提交
15
*/
H
hongming 已提交
16

J
jeff 已提交
17 18 19 20 21
package main

import (
	"bytes"
	"encoding/json"
H
hongming 已提交
22
	"flag"
J
jeff 已提交
23 24 25
	"fmt"
	"github.com/emicklei/go-restful"
	"github.com/emicklei/go-restful-openapi"
Z
zryfish 已提交
26
	"github.com/go-openapi/loads"
H
hongming 已提交
27
	"github.com/go-openapi/spec"
Z
zryfish 已提交
28 29 30
	"github.com/go-openapi/strfmt"
	"github.com/go-openapi/validate"
	"github.com/pkg/errors"
H
hongming 已提交
31
	"io/ioutil"
32
	urlruntime "k8s.io/apimachinery/pkg/util/runtime"
Z
zryfish 已提交
33 34
	"k8s.io/klog"
	authoptions "kubesphere.io/kubesphere/pkg/apiserver/authentication/options"
J
jeff 已提交
35
	"kubesphere.io/kubesphere/pkg/apiserver/runtime"
H
hongming 已提交
36
	"kubesphere.io/kubesphere/pkg/constants"
Z
zryfish 已提交
37
	"kubesphere.io/kubesphere/pkg/informers"
38 39 40
	devopsv1alpha2 "kubesphere.io/kubesphere/pkg/kapis/devops/v1alpha2"
	iamv1alpha2 "kubesphere.io/kubesphere/pkg/kapis/iam/v1alpha2"
	loggingv1alpha2 "kubesphere.io/kubesphere/pkg/kapis/logging/v1alpha2"
R
runzexia 已提交
41
	monitoringv1alpha3 "kubesphere.io/kubesphere/pkg/kapis/monitoring/v1alpha3"
Z
Zhengyi Lai 已提交
42
	networkv1alpha2 "kubesphere.io/kubesphere/pkg/kapis/network/v1alpha2"
43 44 45 46 47 48 49
	openpitrixv1 "kubesphere.io/kubesphere/pkg/kapis/openpitrix/v1"
	operationsv1alpha2 "kubesphere.io/kubesphere/pkg/kapis/operations/v1alpha2"
	resourcesv1alpha2 "kubesphere.io/kubesphere/pkg/kapis/resources/v1alpha2"
	resourcesv1alpha3 "kubesphere.io/kubesphere/pkg/kapis/resources/v1alpha3"
	metricsv1alpha2 "kubesphere.io/kubesphere/pkg/kapis/servicemesh/metrics/v1alpha2"
	tenantv1alpha2 "kubesphere.io/kubesphere/pkg/kapis/tenant/v1alpha2"
	terminalv1alpha2 "kubesphere.io/kubesphere/pkg/kapis/terminal/v1alpha2"
Z
zryfish 已提交
50 51
	"kubesphere.io/kubesphere/pkg/models/iam/am"
	"kubesphere.io/kubesphere/pkg/models/iam/im"
R
runzexia 已提交
52
	"kubesphere.io/kubesphere/pkg/simple/client/devops/fake"
Z
zryfish 已提交
53
	"kubesphere.io/kubesphere/pkg/simple/client/k8s"
R
runzexia 已提交
54
	fakes3 "kubesphere.io/kubesphere/pkg/simple/client/s3/fake"
Z
zryfish 已提交
55
	"kubesphere.io/kubesphere/pkg/version"
J
jeff 已提交
56 57 58
	"log"
)

H
hongming 已提交
59 60 61
var output string

func init() {
R
runzexia 已提交
62
	flag.StringVar(&output, "output", "./api/ks-openapi-spec/swagger.json", "--output=./api.json")
H
hongming 已提交
63 64
}

J
jeff 已提交
65
func main() {
H
hongming 已提交
66
	flag.Parse()
Z
zryfish 已提交
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
	swaggerSpec := generateSwaggerJson()

	err := validateSpec(swaggerSpec)
	if err != nil {
		klog.Warningf("Swagger specification has errors")
	}
}

func validateSpec(apiSpec []byte) error {

	swaggerDoc, err := loads.Analyzed(apiSpec, "")
	if err != nil {
		return err
	}

	// Attempts to report about all errors
	validate.SetContinueOnErrors(true)

	v := validate.NewSpecValidator(swaggerDoc.Schema(), strfmt.Default)
	result, _ := v.Validate(swaggerDoc)

	if result.HasWarnings() {
		log.Printf("See warnings below:\n")
		for _, desc := range result.Warnings {
			log.Printf("- WARNING: %s\n", desc.Error())
		}

	}
	if result.HasErrors() {
		str := fmt.Sprintf("The swagger spec is invalid against swagger specification %s.\nSee errors below:\n", swaggerDoc.Version())
		for _, desc := range result.Errors {
			str += fmt.Sprintf("- %s\n", desc.Error())
		}
		log.Println(str)
		return errors.New(str)
	}

	return nil
J
jeff 已提交
105 106
}

Z
zryfish 已提交
107
func generateSwaggerJson() []byte {
J
jeff 已提交
108

H
hongming 已提交
109
	container := runtime.Container
Z
zryfish 已提交
110 111 112 113 114
	clientsets := k8s.NewNullClient()

	informerFactory := informers.NewNullInformerFactory()

	urlruntime.Must(devopsv1alpha2.AddToContainer(container, informerFactory.KubeSphereSharedInformerFactory(), &fake.Devops{}, nil, clientsets.KubeSphere(), fakes3.NewFakeS3()))
H
hongming 已提交
115
	urlruntime.Must(iamv1alpha2.AddToContainer(container, im.NewOperator(clientsets.KubeSphere(), informerFactory), am.NewReadOnlyOperator(informerFactory), authoptions.NewAuthenticateOptions()))
Z
zryfish 已提交
116
	urlruntime.Must(loggingv1alpha2.AddToContainer(container, clientsets, nil))
H
huanggze 已提交
117
	urlruntime.Must(monitoringv1alpha3.AddToContainer(container, clientsets.Kubernetes(), nil, informerFactory, nil))
Z
zryfish 已提交
118 119 120 121
	urlruntime.Must(openpitrixv1.AddToContainer(container, informerFactory, nil))
	urlruntime.Must(operationsv1alpha2.AddToContainer(container, clientsets.Kubernetes()))
	urlruntime.Must(resourcesv1alpha2.AddToContainer(container, clientsets.Kubernetes(), informerFactory))
	urlruntime.Must(resourcesv1alpha3.AddToContainer(container, informerFactory))
H
hongming 已提交
122
	urlruntime.Must(tenantv1alpha2.AddToContainer(container, informerFactory, nil, nil, nil))
Z
zryfish 已提交
123
	urlruntime.Must(terminalv1alpha2.AddToContainer(container, clientsets.Kubernetes(), nil))
124
	urlruntime.Must(metricsv1alpha2.AddToContainer(container))
125
	urlruntime.Must(networkv1alpha2.AddToContainer(container, ""))
H
hongming 已提交
126

J
jeff 已提交
127
	config := restfulspec.Config{
H
hongming 已提交
128 129
		WebServices:                   container.RegisteredWebServices(),
		PostBuildSwaggerObjectHandler: enrichSwaggerObject}
J
jeff 已提交
130 131 132

	swagger := restfulspec.BuildSwagger(config)

H
hongming 已提交
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
	swagger.Info.Extensions = make(spec.Extensions)
	swagger.Info.Extensions.Add("x-tagGroups", []struct {
		Name string   `json:"name"`
		Tags []string `json:"tags"`
	}{
		{
			Name: "IAM",
			Tags: []string{constants.IdentityManagementTag, constants.AccessManagementTag},
		},
		{
			Name: "Resources",
			Tags: []string{constants.ClusterResourcesTag, constants.NamespaceResourcesTag, constants.UserResourcesTag},
		},
		{
			Name: "Monitoring",
			Tags: []string{constants.ComponentStatusTag},
		},
		{
			Name: "Tenant",
			Tags: []string{constants.TenantResourcesTag},
		},
		{
			Name: "Other",
S
soulseen 已提交
156
			Tags: []string{constants.VerificationTag, constants.RegistryTag},
H
hongming 已提交
157
		},
R
runzexia 已提交
158 159 160 161 162 163
		{
			Name: "DevOps",
			Tags: []string{constants.DevOpsProjectTag, constants.DevOpsProjectCredentialTag,
				constants.DevOpsPipelineTag, constants.DevOpsProjectMemberTag,
				constants.DevOpsWebhookTag, constants.DevOpsJenkinsfileTag, constants.DevOpsScmTag},
		},
H
huanggze 已提交
164 165 166 167 168
		{
			Name: "Monitoring",
			Tags: []string{constants.ClusterMetricsTag, constants.NodeMetricsTag, constants.NamespaceMetricsTag, constants.WorkloadMetricsTag,
				constants.PodMetricsTag, constants.ContainerMetricsTag, constants.WorkspaceMetricsTag, constants.ComponentMetricsTag},
		},
H
huanggze 已提交
169 170
		{
			Name: "Logging",
Z
zryfish 已提交
171
			Tags: []string{constants.LogQueryTag},
H
huanggze 已提交
172
		},
H
hongming 已提交
173 174
	})

R
runzexia 已提交
175
	data, _ := json.MarshalIndent(swagger, "", "  ")
H
hongming 已提交
176 177 178 179 180
	err := ioutil.WriteFile(output, data, 420)
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("successfully written to %s", output)
Z
zryfish 已提交
181 182

	return data
H
hongming 已提交
183
}
J
jeff 已提交
184

H
hongming 已提交
185 186 187 188 189 190 191 192
func enrichSwaggerObject(swo *spec.Swagger) {
	swo.Info = &spec.Info{
		InfoProps: spec.InfoProps{
			Title:       "KubeSphere",
			Description: "KubeSphere OpenAPI",
			Contact: &spec.ContactInfo{
				Name:  "kubesphere",
				Email: "kubesphere@yunify.com",
R
runzexia 已提交
193
				URL:   "https://kubesphere.io",
H
hongming 已提交
194 195 196 197 198
			},
			License: &spec.License{
				Name: "Apache",
				URL:  "http://www.apache.org/licenses/",
			},
Z
zryfish 已提交
199
			Version: version.Version,
H
hongming 已提交
200 201
		},
	}
J
jeff 已提交
202

H
hongming 已提交
203 204 205 206 207
	// setup security definitions
	swo.SecurityDefinitions = map[string]*spec.SecurityScheme{
		"jwt": spec.APIKeyAuth("Authorization", "header"),
	}
	swo.Security = []map[string][]string{{"jwt": []string{}}}
J
jeff 已提交
208 209 210 211 212 213 214 215 216 217 218
}

func apiTree(container *restful.Container) {
	buf := bytes.NewBufferString("\n")
	for _, ws := range container.RegisteredWebServices() {
		for _, route := range ws.Routes() {
			buf.WriteString(fmt.Sprintf("%s %s\n", route.Method, route.Path))
		}
	}
	log.Println(buf.String())
}