Skip to content

Commit

Permalink
feat(bk-bscp): access blueking notification center (#2913)
Browse files Browse the repository at this point in the history
* feat(bk-bscp): access blueking notification center

* feat(bk-bscp): access blueking notification center

* feat(bk-bscp): access blueking notification center
  • Loading branch information
AlkaidChan authored Jan 19, 2024
1 parent 3a123a8 commit fc3f9b7
Show file tree
Hide file tree
Showing 9 changed files with 293 additions and 17 deletions.
19 changes: 2 additions & 17 deletions bcs-services/bcs-bscp/cmd/api-server/api_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,23 +13,8 @@
// Package main is the entry point of the API server.
package main

import (
"fmt"
"os"

"github.com/TencentBlueKing/bk-bcs/bcs-services/bcs-bscp/cmd/api-server/app"
"github.com/TencentBlueKing/bk-bcs/bcs-services/bcs-bscp/cmd/api-server/options"
"github.com/TencentBlueKing/bk-bcs/bcs-services/bcs-bscp/pkg/cc"
"github.com/TencentBlueKing/bk-bcs/bcs-services/bcs-bscp/pkg/logs"
)
import "github.com/TencentBlueKing/bk-bcs/bcs-services/bcs-bscp/cmd/api-server/cmd"

func main() {
cc.InitService(cc.APIServerName)

opts := options.InitOptions()
if err := app.Run(opts); err != nil {
fmt.Fprintf(os.Stderr, "start api server failed, err: %v", err)
logs.CloseLogs()
os.Exit(1)
}
cmd.Execute()
}
82 changes: 82 additions & 0 deletions bcs-services/bcs-bscp/cmd/api-server/cmd/migrate.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
/*
* Tencent is pleased to support the open source community by making Blueking Container Service available.
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* 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.
*/

// Package cmd provides operations for init and upgrading the bk-apigateway resources and
// register the system 'bk-bscp' into bk-notice
package cmd

import (
"context"
"fmt"

"github.com/spf13/cobra"

"github.com/TencentBlueKing/bk-bcs/bcs-services/bcs-bscp/pkg/cc"
"github.com/TencentBlueKing/bk-bcs/bcs-services/bcs-bscp/pkg/components/bknotice"
)

var migrateCmd = &cobra.Command{
Use: "migrate",
Short: "api-server migrations tool",
Run: func(cmd *cobra.Command, args []string) {

},
}

var migrateInitNoticeCmd = &cobra.Command{
Use: "init-notice",
Short: "Register system 'bk-bscp' into bk-notice",
Run: func(cmd *cobra.Command, args []string) {

if err := cc.LoadSettings(SysOpt.Sys); err != nil {
fmt.Println("load settings from config files failed, err:", err)
return
}

if !cc.ApiServer().BKNotice.Enable {
fmt.Println("bknotice is disabled, skip init")
return
}

if err := bknotice.RegisterSystem(context.Background()); err != nil {
fmt.Println("register system to bknotice failed, err:", err)
return
}
},
}

var migrateInitApigatewayCmd = &cobra.Command{
Use: "init-apigateway",
Short: "Create 'bk-bscp' apigateway instance and upgrade api resources",
Run: func(cmd *cobra.Command, args []string) {

if err := cc.LoadSettings(SysOpt.Sys); err != nil {
fmt.Println("load settings from config files failed, err:", err)
return
}

fmt.Println("Need to be implemented")
},
}

func init() {

// Add "--debug" flag to all migrate sub commands
migrateCmd.PersistentFlags().BoolP("debug", "d", false,
"whether to debug output the execution process,, default is false")

migrateCmd.AddCommand(migrateInitNoticeCmd)
migrateCmd.AddCommand(migrateInitApigatewayCmd)

// Add "migrate" command to the root command
rootCmd.AddCommand(migrateCmd)
}
58 changes: 58 additions & 0 deletions bcs-services/bcs-bscp/cmd/api-server/cmd/root.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/*
* Tencent is pleased to support the open source community by making Blueking Container Service available.
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* 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.
*/

package cmd

import (
"fmt"
"os"

"github.com/spf13/cobra"

"github.com/TencentBlueKing/bk-bcs/bcs-services/bcs-bscp/cmd/api-server/app"
"github.com/TencentBlueKing/bk-bcs/bcs-services/bcs-bscp/cmd/api-server/options"
"github.com/TencentBlueKing/bk-bcs/bcs-services/bcs-bscp/pkg/cc"
"github.com/TencentBlueKing/bk-bcs/bcs-services/bcs-bscp/pkg/logs"
)

// SysOpt is the system option
var SysOpt *options.Option

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "bk-bscp-apiserver",
Short: "BSCP ApiServer",
Run: func(cmd *cobra.Command, args []string) {

if err := app.Run(SysOpt); err != nil {
fmt.Fprintf(os.Stderr, "start api server failed, err: %v", err)
logs.CloseLogs()
os.Exit(1)
}

},
}

// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
cobra.CheckErr(rootCmd.Execute())
}

func init() {

rootCmd.CompletionOptions.DisableDefaultCmd = true

SysOpt = options.InitOptions()

cc.InitService(cc.APIServerName)
}
74 changes: 74 additions & 0 deletions bcs-services/bcs-bscp/cmd/api-server/service/bknotice.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/*
* Tencent is pleased to support the open source community by making Blueking Container Service available.
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* 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.
*/

package service

import (
"fmt"
"io"
"net/http"

"github.com/TencentBlueKing/bk-bcs/bcs-services/bcs-bscp/pkg/cc"
"github.com/TencentBlueKing/bk-bcs/bcs-services/bcs-bscp/pkg/config"
)

// bkNoticeService is http handler for bknotice service.
type bkNoticeService struct {
}

// GetCurrentAnnouncements get current announcements
func (s *bkNoticeService) GetCurrentAnnouncements(w http.ResponseWriter, r *http.Request) {
// Prepare the new request

proxyURL := fmt.Sprintf("%s/v1/announcement/get_current_announcements/?platform=%s",
config.G.Base.AppCode, cc.ApiServer().BKNotice.Host)

proxyReq, err := http.NewRequest("GET", proxyURL, nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}

authHeader := fmt.Sprintf("{\"bk_app_code\": \"%s\", \"bk_app_secret\": \"%s\"}",
config.G.Base.AppCode, config.G.Base.AppSecret)

proxyReq.Header.Set("X-Bkapi-Authorization", authHeader)

// Send the request to the target API
client := &http.Client{}
resp, err := client.Do(proxyReq)
if err != nil {
http.Error(w, err.Error(), http.StatusBadGateway)
return
}
defer resp.Body.Close()

// Copy the response headers and status code
for key, values := range resp.Header {
for _, value := range values {
w.Header().Add(key, value)
}
}
w.WriteHeader(resp.StatusCode)

_, err = io.Copy(w, resp.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}

func newBKNoticeService() (*bkNoticeService, error) {

service := &bkNoticeService{}

return service, nil
}
7 changes: 7 additions & 0 deletions bcs-services/bcs-bscp/cmd/api-server/service/proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ type proxy struct {
cfgSvrMux *runtime.ServeMux
authSvrMux http.Handler
repo *repoService
bkNotice *bkNoticeService
state serviced.State
authorizer auth.Authorizer
cfgClient pbcs.ConfigClient
Expand Down Expand Up @@ -71,6 +72,11 @@ func newProxy(dis serviced.Discover) (*proxy, error) {
return nil, err
}

bkNotice, err := newBKNoticeService()
if err != nil {
return nil, err
}

cfgClient, err := newCfgClient(dis)
if err != nil {
return nil, err
Expand All @@ -84,6 +90,7 @@ func newProxy(dis serviced.Discover) (*proxy, error) {
p := &proxy{
cfgSvrMux: cfgSvrMux,
repo: repo,
bkNotice: bkNotice,
configImportService: configImportService,
state: state,
authorizer: authorizer,
Expand Down
5 changes: 5 additions & 0 deletions bcs-services/bcs-bscp/cmd/api-server/service/routers.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,5 +162,10 @@ func (p *proxy) routers() http.Handler {
r.Post("/", p.configImportService.ConfigFileImport)
})

// 获取通知中心通知列表
r.Route("/api/v1/announcements", func(r chi.Router) {
r.Get("/", p.bkNotice.GetCurrentAnnouncements)
})

return r
}
1 change: 1 addition & 0 deletions bcs-services/bcs-bscp/pkg/cc/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ type ApiServerSetting struct {
Service Service `yaml:"service"`
Log LogOption `yaml:"log"`
Repo Repository `yaml:"repository"`
BKNotice BKNotice `yaml:"bkNotice"`
FeatureFlags map[FeatureFlag]FeatureFlagOption `yaml:"featureFlags"`
}

Expand Down
6 changes: 6 additions & 0 deletions bcs-services/bcs-bscp/pkg/cc/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -1033,3 +1033,9 @@ func (v *Vault) getConfigFromEnv() {
v.Token = os.Getenv(VaultTokenEnv)
v.Address = os.Getenv(VaultAddressEnv)
}

// BKNotice defines all the bk notice related runtime.
type BKNotice struct {
Enable bool `yaml:"enable"`
Host string `yaml:"host"`
}
58 changes: 58 additions & 0 deletions bcs-services/bcs-bscp/pkg/components/bknotice/bknotice.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/*
* Tencent is pleased to support the open source community by making Blueking Container Service available.
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* 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.
*/

// Package bknotice provides bknotice client.
package bknotice

import (
"context"
"encoding/json"
"fmt"

"github.com/TencentBlueKing/bk-bcs/bcs-services/bcs-bscp/pkg/cc"
"github.com/TencentBlueKing/bk-bcs/bcs-services/bcs-bscp/pkg/components"
"github.com/TencentBlueKing/bk-bcs/bcs-services/bcs-bscp/pkg/config"
)

type registerSystemResp struct {
Result bool `json:"result"`
Code int `json:"code"`
Message string `json:"message"`
}

// RegisterSystem 注册系统到通知中心
func RegisterSystem(ctx context.Context) error {
url := fmt.Sprintf("%s/v1/register/", cc.ApiServer().BKNotice.Host)

authHeader := fmt.Sprintf("{\"bk_app_code\": \"%s\", \"bk_app_secret\": \"%s\"}",
config.G.Base.AppCode, config.G.Base.AppSecret)

resp, err := components.GetClient().R().
SetContext(ctx).
SetHeader("X-Bkapi-Authorization", authHeader).
Post(url)

if err != nil {
return err
}

resigerResp := &registerSystemResp{}
if err := json.Unmarshal(resp.Body(), resigerResp); err != nil {
return err
}

if resigerResp.Code != 0 {
return fmt.Errorf("register system to bknotice failed, code: %d, message: %s",
resigerResp.Code, resigerResp.Message)
}
return nil
}

0 comments on commit fc3f9b7

Please sign in to comment.