Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Daemon process #18

Merged
merged 26 commits into from
Aug 25, 2017
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
5 changes: 3 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,8 @@ print-% :
# perform go build on project
go-build :
go build -o bin/hostnic $(GO_BUILD_FLAGS) $(GIT_REPOSITORY)/cmd/hostnic/
go build -o bin/nicclearner $(GO_BUILD_FLAGS) $(GIT_REPOSITORY)/cmd/niccleaner/
go build -o bin/daemon $(GO_BUILD_FLAGS) $(GIT_REPOSITORY)/cmd/daemon/


.PHONY : default all go-build

.PHONY : default all go-build
104 changes: 104 additions & 0 deletions cmd/daemon/cmd/root.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
// Copyright © 2017 NAME HERE <EMAIL ADDRESS>
// 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.

package cmd

import (
"fmt"
"os"

homedir "github.com/mitchellh/go-homedir"
"github.com/spf13/cobra"
"github.com/spf13/viper"
log "github.com/sirupsen/logrus"
)

var cfgFile string
var logLevel string

// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
Use: "daemon",
Short: "A brief description of your application",
Long: `A longer description that spans multiple lines and likely contains
examples and usage of using your application. For example:

Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
// Uncomment the following line if your bare application
// has an action associated with it:
// Run: func(cmd *cobra.Command, args []string) { },
}

// 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() {
if err := RootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}

func init() {
cobra.OnInitialize(initConfig)

// Here you will define your flags and configuration settings.
// Cobra supports persistent flags, which, if defined here,
// will be global for your application.
RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.daemon.yaml)")
RootCmd.PersistentFlags().StringVar(&logLevel, "loglevel", "info","daemon process log level(debug,info,warn,error)")

// Cobra also supports local flags, which will only run
// when this action is called directly.
RootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
// Find home directory.
home, err := homedir.Dir()
if err != nil {
fmt.Println(err)
os.Exit(1)
}

// Search config in home directory with name ".daemon" (without extension).
viper.AddConfigPath(home)
viper.SetConfigName(".daemon")
}

viper.AutomaticEnv() // read in environment variables that match

// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
fmt.Println("Using config file:", viper.ConfigFileUsed())
}

switch logLevel {
case "debug":
log.SetLevel(log.DebugLevel)
case "info":
log.SetLevel(log.InfoLevel)
case "warn":
log.SetLevel(log.WarnLevel)
case "error":
log.SetLevel(log.ErrorLevel)
default:
log.SetLevel(log.InfoLevel)
}
}
127 changes: 127 additions & 0 deletions cmd/daemon/cmd/start.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
// Copyright © 2017 NAME HERE <EMAIL ADDRESS>
// 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.

package cmd

import (
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/yunify/hostnic-cni/pkg/messages"
"github.com/yunify/hostnic-cni/pkg/provider/qingcloud"
"github.com/yunify/hostnic-cni/pkg/server"
"google.golang.org/grpc"
"net"
"os"
"os/signal"
"syscall"
"time"
)

const (
gracefulTimeout = 120 * time.Second
)

// startCmd represents the start command
var startCmd = &cobra.Command{
Use: "start",
Short: "A brief description of your command",
Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command. For example:

Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
Run: func(cmd *cobra.Command, args []string) {
resourceProvider, err := qingcloud.NewQCNicProvider(viper.GetString("QyAccessFilePath"), viper.GetStringSlice("vxnets"))
if err != nil {
log.Errorf("Failed to initiate resource provider, %v", err)
}

//setup nic pool
nicpool, err := server.NewNicPool(viper.GetInt("PoolSize"), resourceProvider)
if err != nil {
log.Errorf("Failed to create pool. %v", err)
return
}
//start up server rpc routine
listener, err := net.Listen("tcp", viper.GetString("bindAddr"))
if err != nil {
log.Errorf("Failed to listen to assigned port, %v", err)
return
}
grpcServer := grpc.NewServer()
messages.RegisterNicservicesServer(grpcServer, server.NewDaemonServerHandler(nicpool))
go grpcServer.Serve(listener)

signalCh := make(chan os.Signal, 4)
signal.Notify(signalCh, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP)
var sig os.Signal

WAIT:
select {
case s := <-signalCh:
sig = s
}

if sig == syscall.SIGHUP {
//TODO implement refresh config logic
goto WAIT
}
//Attempt a graceful shutdown

log.Infof("Got interrupt call, graceful shutdown...")
gracefulCh := make(chan struct{})
go func() {
log.Infof("Shutdown grpc server")
grpcServer.GracefulStop()
log.Infof("Shutdown nic pool server")
nicpool.ShutdownNicPool()
close(gracefulCh)
}()

select {
case <-signalCh:
return
case <-time.After(gracefulTimeout):
return
case <-gracefulCh:
return
}
},
}

func init() {
RootCmd.AddCommand(startCmd)

// Here you will define your flags and configuration settings.

// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// startCmd.PersistentFlags().String("foo", "", "A help for foo")

// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// startCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")

//server routine properties
startCmd.Flags().String("bindAddr", ":31080", "port of daemon process(e.g. socket port 127.0.0.1:31080 [fe80::1%lo0]:80 )")

//sdk properties
startCmd.Flags().String("QyAccessFilePath", "/etc/qingcloud/client.yaml", "Path of QingCloud Access file")
startCmd.Flags().StringSlice("vxnets", []string{}, "ids of vxnet")

//pool properties
startCmd.Flags().Int("PoolSize", 3, "The size of nic pool")
viper.BindPFlags(startCmd.Flags())
}
52 changes: 52 additions & 0 deletions cmd/daemon/cmd/version.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// Copyright © 2017 NAME HERE <EMAIL ADDRESS>
// 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.

package cmd

import (
"fmt"

"github.com/spf13/cobra"
"github.com/yunify/hostnic-cni/pkg"
)

// versionCmd represents the version command
var versionCmd = &cobra.Command{
Use: "version",
Short: "A brief description of your command",
Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command. For example:

Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
Run: func(cmd *cobra.Command, args []string) {
fmt.Printf("VERSION: %s\n", pkg.VERSION)
fmt.Printf("GIT_SHA1: %s\n", pkg.GIT_SHA1)
fmt.Printf("BUILD_LABEL: %s\n", pkg.BUILD_LABEL)
},
}

func init() {
RootCmd.AddCommand(versionCmd)

// Here you will define your flags and configuration settings.

// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// versionCmd.PersistentFlags().String("foo", "", "A help for foo")

// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// versionCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
20 changes: 20 additions & 0 deletions cmd/daemon/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// Copyright © 2017 NAME HERE <EMAIL ADDRESS>
// 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.

package main

import "github.com/yunify/hostnic-cni/cmd/daemon/cmd"

func main() {
cmd.Execute()
}
Loading