func NewServer(cfg *config.Config) (*Server, error) { s := new(Server) s.cfg = cfg s.counter = new(Counter) s.addr = cfg.Addr s.user = cfg.User s.password = cfg.Password atomic.StoreInt32(&s.logSqlIndex, 0) s.logSql[s.logSqlIndex] = cfg.LogSql atomic.StoreInt32(&s.slowLogTimeIndex, 0) s.slowLogTime[s.slowLogTimeIndex] = cfg.SlowLogTime if len(cfg.Charset) != 0 { cid, ok := mysql.CharsetIds[cfg.Charset] if !ok { return nil, errors.ErrInvalidCharset } s.charset = cfg.Charset s.collation = cid } else { s.charset = mysql.DEFAULT_CHARSET s.collation = mysql.DEFAULT_COLLATION_ID } if err := s.parseBlackListSqls(); err != nil { return nil, err } if err := s.parseAllowIps(); err != nil { return nil, err } if err := s.parseNodes(); err != nil { return nil, err } if err := s.parseSchema(); err != nil { return nil, err } var err error netProto := "tcp" s.listener, err = net.Listen(netProto, s.addr) if err != nil { return nil, err } golog.Info("server", "NewServer", "Server running", 0, "netProto", netProto, "address", s.addr) return s, nil }
func main() { fmt.Print(banner) runtime.GOMAXPROCS(runtime.NumCPU()) flag.Parse() fmt.Printf("Git commit:%s\n", hack.Version) fmt.Printf("Build time:%s\n", hack.Compile) if *version { return } if len(*configFile) == 0 { fmt.Println("must use a config file") return } cfg, err := config.ParseConfigFile(*configFile) if err != nil { fmt.Printf("parse config file error:%v\n", err.Error()) return } //when the log file size greater than 1GB, kingshard will generate a new file if len(cfg.LogPath) != 0 { sysFilePath := path.Join(cfg.LogPath, sysLogName) sysFile, err := golog.NewRotatingFileHandler(sysFilePath, MaxLogSize, 1) if err != nil { fmt.Printf("new log file error:%v\n", err.Error()) return } golog.GlobalSysLogger = golog.New(sysFile, golog.Lfile|golog.Ltime|golog.Llevel) sqlFilePath := path.Join(cfg.LogPath, sqlLogName) sqlFile, err := golog.NewRotatingFileHandler(sqlFilePath, MaxLogSize, 1) if err != nil { fmt.Printf("new log file error:%v\n", err.Error()) return } golog.GlobalSqlLogger = golog.New(sqlFile, golog.Lfile|golog.Ltime|golog.Llevel) } if *logLevel != "" { setLogLevel(*logLevel) } else { setLogLevel(cfg.LogLevel) } var svr *server.Server svr, err = server.NewServer(cfg) if err != nil { golog.Error("main", "main", err.Error(), 0) golog.GlobalSysLogger.Close() golog.GlobalSqlLogger.Close() return } sc := make(chan os.Signal, 1) signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT) go func() { sig := <-sc golog.Info("main", "main", "Got signal", 0, "signal", sig) golog.GlobalSysLogger.Close() golog.GlobalSqlLogger.Close() svr.Close() }() svr.Run() }