Example #1
0
func main() {

	junk, err := flags.ParseArgs(&opts, os.Args)

	if len(junk) != 1 {
		fmt.Printf("Usage: Invalid arguments supplied, %s\n", junk)
		os.Exit(1)
	}
	if err != nil {
		os.Exit(1)
	}

	port = fmt.Sprintf("%d", opts.Port)
	if opts.HostIP != "localhost" {
		host_ip = opts.HostIP
	}

	server, err := socketio.NewServer(nil)
	if err != nil {
		log.Fatal(err)
	}
	server.On("connection", func(so socketio.Socket) {
		log.Println("on connection")
		so.Join("chat")
		so.On("chat message", func(msg string) {
			m := make(map[string]interface{})
			m["a"] = "你好" // hello there
			e := so.Emit("cn1111", m)
			//这个没有问题			// this is no problem
			fmt.Println("\n\n")

			b := make(map[string]string)
			b["u-a"] = "中文内容" //这个不能是中文		// this is chineese // this can not be chineese
			m["b-c"] = b
			e = so.Emit("cn2222", m)
			log.Println(e)

			log.Println("emit:", so.Emit("chat message", msg))
			so.BroadcastTo("chat", "chat message", msg)
		})
		so.On("t45", func(msg string) {
			err := so.Emit("r45", "Yep")
			if err != nil {
				fmt.Printf("Error: %s\n", err)
			}
		})
		so.On("disconnection", func() {
			log.Println("on disconnect")
		})
	})
	server.On("error", func(so socketio.Socket, err error) {
		log.Println("error:", err)
	})

	http.Handle("/socket.io/", server)
	http.Handle("/", http.FileServer(http.Dir("./asset")))
	fmt.Printf("Serving on port %s, brows to http://localhost:%s/\n", port, port)
	listen := fmt.Sprintf("%s:%s", host_ip, port)
	log.Fatal(http.ListenAndServe(listen, nil))
}
Example #2
0
func TestCoreLoopRetryDidRetry(t *testing.T) {
	oldopts := opts
	defer func() { opts = oldopts }()

	statefile, err := ioutil.TempFile("./testdata", "")
	if err != nil {
		t.Fatal(err)
	}

	defer func() {
		os.Remove(statefile.Name())
		statefile.Close()
	}()

	arguments := "--retries=3 -- ./testdata/works-after-two-failures.sh " + statefile.Name()
	args, err := flags.ParseArgs(&opts, strings.Fields(arguments))
	if err != nil {
		t.Fatal(err)
	}

	var output bytes.Buffer
	var logstream bytes.Buffer

	log.SetOutput(&output)

	err = CoreLoopRetry(args, &logstream)
	t.Log(output.String())
	t.Log(logstream.String())
	if err != nil {
		t.Error("want no error, got", err)
	}
}
Example #3
0
func main() {

	_, err := flags.ParseArgs(&opts, os.Args)
	if err != nil {
		os.Exit(1)
	}

	if opts.ClearTopic {
		clearTopic(opts.Topic)
	}

	if opts.KeyPrefix != "" {
		KEY_PREFIX = opts.KeyPrefix + "-"
	}

	if opts.ProcessorHost != "" {
		if !strings.HasSuffix(opts.ProcessorHost, "/") {
			PROCESSOR_HOST = opts.ProcessorHost
		} else {
			fmt.Println("Cannot have a hostname that ends with a slash, try again.")
			os.Exit(1)
		}
	}

	if opts.ProcessorPort != "" {
		PROCESSOR_PORT = opts.ProcessorPort
	}

	err = filepath.Walk(string(opts.Path), visit)
	if err != nil {
		fmt.Printf("Error saving log files: %s\n", err)
	}
}
Example #4
0
func init() {
	_, err := flags.ParseArgs(&options, os.Args)

	if err != nil {
		os.Exit(1)
	}
}
Example #5
0
func main() {
	var opts struct {
		DBPath   string `short:"f" long:"file" description:"Path to GeoIP database" value-name:"FILE" default:""`
		Listen   string `short:"l" long:"listen" description:"Listening address" value-name:"ADDR" default:":8080"`
		CORS     bool   `short:"x" long:"cors" description:"Allow requests from other domains" default:"false"`
		Template string `short:"t" long:"template" description:"Path to template" default:"index.html"`
	}
	_, err := flags.ParseArgs(&opts, os.Args)
	if err != nil {
		os.Exit(1)
	}

	var a *api.API
	if opts.DBPath == "" {
		a = api.New()
	} else {
		a, err = api.NewWithGeoIP(opts.DBPath)
		if err != nil {
			log.Fatal(err)
		}
	}

	a.CORS = opts.CORS
	a.Template = opts.Template

	log.Printf("Listening on %s", opts.Listen)
	if err := a.ListenAndServe(opts.Listen); err != nil {
		log.Fatal(err)
	}
}
Example #6
0
func getDefaultOptions() *options {
	opts := &options{}
	if _, err := gflags.ParseArgs(opts, nil); err != nil {
		panic(err)
	}
	opts.PProfOptions.BinaryFile = testPProfInputFile
	return opts
}
Example #7
0
func TestPuppetDetailedExitCodes(t *testing.T) {
	oldopts := opts
	defer func() { opts = oldopts }()

	arguments := "--monitor-ok=2 --monitor-warning=4 --monitor-warning=6 --monitor-critical=1 -- true"
	_, err := flags.ParseArgs(&opts, strings.Fields(arguments))
	err = validateOptionConstraints()
	if err != nil {
		t.Errorf("want no error, got %s", err)
	}
}
Example #8
0
func TestDefaulSettingsOk(t *testing.T) {
	oldopts := opts
	defer func() { opts = oldopts }()

	arguments := "-- true"
	_, err := flags.ParseArgs(&opts, strings.Fields(arguments))
	err = validateOptionConstraints()
	if err != nil {
		t.Errorf("want no error, got %s", err)
	}

}
Example #9
0
func runWithArgs(args ...string) error {
	opts := &options{}
	if _, err := gflags.ParseArgs(opts, args); err != nil {
		if flagErr, ok := err.(*gflags.Error); ok && flagErr.Type == gflags.ErrHelp {
			os.Exit(0)
		}
		return fmt.Errorf("could not parse options: %v", err)
	}
	if err := validateOptions(opts); err != nil {
		return fmt.Errorf("invalid options: %v", err)
	}

	return runWithOptions(opts)
}
Example #10
0
func TestCoreLoopOncePosixExitHandling(t *testing.T) {
	testone := func(arguments string) (error, monitoringResult) {
		logbuf := func(t *testing.T, buf *bytes.Buffer) {
			if buf.Len() > 0 {
				t.Log(buf.String())
			}
		}

		var output bytes.Buffer
		defer logbuf(t, &output)
		log.SetOutput(&output)
		defer log.SetOutput(&bytes.Buffer{})

		oldopts := opts
		defer func() { opts = oldopts }()

		args, err := flags.ParseArgs(&opts, strings.Fields(arguments))
		if err != nil {
			t.Fatal(err)
		}

		err = validateOptionConstraints()
		if err != nil {
			t.Fatal(err)
		}

		var logstream bytes.Buffer
		defer logbuf(t, &logstream)

		err = CoreLoopOnce(args, &logstream)
		code, _ := error2exit(err)

		return err, code
	}

	for i := 1; i < 256; i++ {
		err, code := testone(fmt.Sprintf("-- ./testdata/exit_with_code.sh %d", i))
		if code != monitorCritical {
			t.Errorf("want CRITICAL monitoring state for exit code %d, got %s due to err = %v", i, code, err)
		}
	}

	for i := monitorOk; i <= monitorUnknown; i++ {
		err, code := testone(fmt.Sprintf("--wrap-nagios-plugin -- ./testdata/exit_with_code.sh %d", i))
		if code != i {
			t.Errorf("want %s monitoring state, got %s due to err = %v", i, code, err)
		}
	}
}
Example #11
0
func main() {
	var opts struct {
		CountryDBPath string `short:"f" long:"country-db" description:"Path to GeoIP country database" value-name:"FILE" default:""`
		CityDBPath    string `short:"c" long:"city-db" description:"Path to GeoIP city database" value-name:"FILE" default:""`
		Listen        string `short:"l" long:"listen" description:"Listening address" value-name:"ADDR" default:":8080"`
		ReverseLookup bool   `short:"r" long:"reverse-lookup" description:"Perform reverse hostname lookups"`
		PortLookup    bool   `short:"p" long:"port-lookup" description:"Enable port lookup"`
		Template      string `short:"t" long:"template" description:"Path to template" default:"index.html"`
		IPHeader      string `short:"H" long:"trusted-header" description:"Header to trust for remote IP, if present (e.g. X-Real-IP)"`
	}
	_, err := flags.ParseArgs(&opts, os.Args)
	if err != nil {
		os.Exit(1)
	}

	oracle := api.NewOracle()
	if opts.ReverseLookup {
		log.Println("Enabling reverse lookup")
		oracle.EnableLookupAddr()
	}
	if opts.PortLookup {
		log.Println("Enabling port lookup")
		oracle.EnableLookupPort()
	}
	if opts.CountryDBPath != "" {
		log.Printf("Enabling country lookup (using database: %s)", opts.CountryDBPath)
		if err := oracle.EnableLookupCountry(opts.CountryDBPath); err != nil {
			log.Fatal(err)
		}
	}
	if opts.CityDBPath != "" {
		log.Printf("Enabling city lookup (using database: %s)", opts.CityDBPath)
		if err := oracle.EnableLookupCity(opts.CityDBPath); err != nil {
			log.Fatal(err)
		}
	}
	if opts.IPHeader != "" {
		log.Printf("Trusting header %s to contain correct remote IP", opts.IPHeader)
	}

	api := api.New(oracle)
	api.Template = opts.Template
	api.IPHeader = opts.IPHeader

	log.Printf("Listening on %s", opts.Listen)
	if err := api.ListenAndServe(opts.Listen); err != nil {
		log.Fatal(err)
	}
}
Example #12
0
func TestCoreLoopOnceExitSuccess(t *testing.T) {
	oldopts := opts
	defer func() { opts = oldopts }()

	arguments := "-- true"
	args, err := flags.ParseArgs(&opts, strings.Fields(arguments))
	if err != nil {
		t.Fatal(err)
	}

	var output bytes.Buffer
	log.SetOutput(&output)

	err = CoreLoopOnce(args, &bytes.Buffer{})
	t.Log(output.String())
	if err != nil {
		t.Error("want no error, got", err)
	}
}
Example #13
0
func main() {
	_, err := flags.ParseArgs(&opts, os.Args)
	PanicIf(err)

	m := martini.Classic()
	m.Map(SetupDB())

	// Serve static files from "static" directory.
	StaticOptions := martini.StaticOptions{Prefix: "static"}
	m.Use(martini.Static(opts.StaticDir, StaticOptions))

	// Render html templates from "templates" directory.
	m.Use(render.Renderer(render.Options{Directory: opts.TemplatesDir}))

	m.Get("/", IndexHandler)
	m.Post("/subscribe/", binding.Form(Subscription{}), SubscribeHandler)

	m.Run()
}
Example #14
0
func TestCoreLoopRetryExitSuccessFunnyExitCodes(t *testing.T) {
	oldopts := opts
	defer func() { opts = oldopts }()

	arguments := "--retries=3 --monitor-ok=1 -- false"
	args, err := flags.ParseArgs(&opts, strings.Fields(arguments))
	if err != nil {
		t.Fatal(err)
	}

	var output bytes.Buffer
	log.SetOutput(&output)

	err = CoreLoopRetry(args, &bytes.Buffer{})
	t.Log(output.String())
	if err != nil {
		t.Error("want no error, got", err)
	}
}
Example #15
0
func parseFlags(flags interface{}, args []string) []string {
	args, err := goflags.ParseArgs(flags, args)
	if err != nil {
		// assert the err to be a flags.Error
		flagError := err.(*goflags.Error)
		if flagError.Type == goflags.ErrHelp {
			// user asked for help on flags.
			// program can exit successfully
			os.Exit(0)
		}
		if flagError.Type == goflags.ErrUnknownFlag {
			fmt.Println("Use --help to view all available options.")
			os.Exit(1)
		}
		fmt.Printf("Error parsing flags: %s\n", err)
		os.Exit(1)
	}
	return args
}
Example #16
0
// Parses the command-line arguments, and validates them.
func parseArgs(args []string) (opts *AppConfig, err error) {
	opts = &AppConfig{}

	_, err = goflags.ParseArgs(opts, args)
	if err != nil {
		return
	}

	// fix bad values...
	if opts.Clients < MIN_LOAD {
		opts.Clients = MIN_LOAD
	}

	if opts.Duration < MIN_RUN_TIME {
		opts.Duration = MIN_RUN_TIME
	}

	opts.d = time.Duration(opts.Duration) * time.Second
	return
}
Example #17
0
func TestDuplicateExitCodes(t *testing.T) {
	oldopts := opts
	defer func() { opts = oldopts }()

	arguments := "--monitor-ok=2 --monitor-warning=4 --monitor-critical=2 -- true"
	_, err := flags.ParseArgs(&opts, strings.Fields(arguments))
	err = validateOptionConstraints()
	if err == nil {
		t.Error("want error, got nil")
	} else if e, ok := err.(*FlagConstraintError); ok {
		want := "is already considered"
		if !strings.Contains(e.Constraint, want) {
			t.Errorf("want %s, got %s", want, err)
		} else {
			t.Log("got", err)
		}
	} else {
		t.Error("want flag constraint error, got", err)
	}
}
Example #18
0
func TestTooBigMaxDelay(t *testing.T) {
	oldopts := opts
	defer func() { opts = oldopts }()

	arguments := "--timeout=1s --max-start-delay=2s -- true"
	_, err := flags.ParseArgs(&opts, strings.Fields(arguments))
	err = validateOptionConstraints()
	if err == nil {
		t.Error("want error, got nil")
	} else if e, ok := err.(*FlagConstraintError); ok {
		want := "max delay >= timeout, no time left for actual command execution"
		if e.Constraint != want {
			t.Errorf("want %s, got %s", want, err)
		} else {
			t.Log("got", err)
		}
	} else {
		t.Error("want flag constraint error, got", err)
	}

}
Example #19
0
func TestCoreLoopOnceWrongCommand(t *testing.T) {
	oldopts := opts
	defer func() { opts = oldopts }()

	arguments := "-- /var/run/nonexistant"
	args, err := flags.ParseArgs(&opts, strings.Fields(arguments))
	if err != nil {
		t.Fatal(err)
	}

	var output bytes.Buffer
	log.SetOutput(&output)

	err = CoreLoopOnce(args, &bytes.Buffer{})
	t.Log(output.String())
	if err == nil {
		t.Error("want error, got nil")
	} else if _, ok := err.(*NotAvailableError); ok {
		t.Log("got", err)
	} else {
		t.Error("want not available error, got", err)
	}
}
Example #20
0
func TestCoreLoopOnceSoftTimeout(t *testing.T) {
	oldopts := opts
	defer func() { opts = oldopts }()

	arguments := "--timeout=100ms --grace-time=50ms -- sleep 1"
	args, err := flags.ParseArgs(&opts, strings.Fields(arguments))
	if err != nil {
		t.Fatal(err)
	}

	var output bytes.Buffer
	log.SetOutput(&output)

	err = CoreLoopOnce(args, &bytes.Buffer{})
	t.Log(output.String())
	if err == nil {
		t.Error("want error, got nil")
	} else if timeout, ok := err.(*TimeoutError); ok && timeout.soft {
		t.Log("got", err)
	} else {
		t.Error("want soft timeout error, got ", err)
	}
}
Example #21
0
func TestCoreLoopRetryExitError(t *testing.T) {
	oldopts := opts
	defer func() { opts = oldopts }()

	arguments := "--retries=3 -- false"
	args, err := flags.ParseArgs(&opts, strings.Fields(arguments))
	if err != nil {
		t.Fatal(err)
	}

	var output bytes.Buffer
	log.SetOutput(&output)

	err = CoreLoopRetry(args, &bytes.Buffer{})
	t.Log(output.String())
	if err == nil {
		t.Error("want error, got nil")
	} else if _, ok := err.(*exec.ExitError); ok {
		t.Log("got", err)
	} else {
		t.Error("want exit error, got", err)
	}
}
Example #22
0
func main() {
	var opts struct {
		BufferSize int    `short:"b" long:"buffer-size" description:"Number of events to buffer" value-name:"COUNT" default:"100"`
		Config     string `short:"f" long:"config" description:"Config file" value-name:"FILE" default:"~/.gounpackrc"`
		Test       bool   `short:"t" long:"test" description:"Test and print config"`
		LogLevel   string `short:"L" long:"log-level" description:"Log level to use" default:"info" choice:"debug" choice:"info" choice:"warn" choice:"error" choice:"fatal" choice:"panic"`
	}

	_, err := flags.ParseArgs(&opts, os.Args)
	if err != nil {
		os.Exit(1)
	}

	cfg, err := dispatcher.ReadConfig(opts.Config)
	if err != nil {
		log.Fatal(err)
	}

	if opts.Test {
		json, err := cfg.JSON()
		if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("%s\n", json)
		return
	}

	log := logrus.New()
	level, err := logrus.ParseLevel(opts.LogLevel)
	if err != nil {
		log.Fatal(err)
	}
	log.Level = level

	dispatcher.New(cfg, opts.BufferSize, unpack.OnFile, log).Serve()
}
Example #23
0
func main() {

	tmp1, err := flags.ParseArgs(&opts, os.Args)
	if err != nil {
		panic(err)
		os.Exit(1)
	}
	flist := tmp1[1:]

	// Get to the correct directory to run stuff from
	if opts.CdTo != "" {
		err := os.Chdir(opts.CdTo)
		if err != nil {
			fmt.Printf("Unable to change directories to %s, error: %s\n", opts.CdTo, err)
			os.Exit(1)
		}
	}

	var gCfg JSONCfg

	// Read in JSON config file if it exists
	if Exists(opts.Cfg) {
		fb, err := ioutil.ReadFile(opts.Cfg)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error reading config file %s, %s\n", opts.Cfg, err)
			os.Exit(1)
		}

		err = json.Unmarshal(fb, &gCfg)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error reading config file %s, %s - file did not parse\n", opts.Cfg, err)
			os.Exit(1)
		}

		fmt.Printf("Config file %s read in, watching %s\n", opts.Cfg, gCfg.FilesToWatch)

		flist = append(flist, gCfg.FilesToWatch...)
		if gCfg.CmdToRun != "" {
			opts.Cmd = gCfg.CmdToRun
		}
		if gCfg.CdTo != "" {
			opts.CdTo = gCfg.CdTo
		}
	}

	// setup signal handler to ignore some signals
	go handleSignals()

	// Delcare stuff --------------------------------------------------------------------------------------
	cli_buf := strings.Split(opts.Cmd, " ")

	// Do periodic Stuff ----------------------------------------------------------------------------------
	ticker := time.NewTicker(1 * time.Second)
	quit := make(chan struct{})
	go func() {
		for {
			// fmt.Printf("AT: %s\n", godebug.LF())
			select {
			case <-ticker.C:
				// do stuff
				if getClearRunCmd() {
					// setRunCmd(false)
					// fmt.Printf("AT: %s\n", godebug.LF())
					cmd := exec.Command(cli_buf[0], cli_buf[1:]...)
					// cmd.Stdin = strings.NewReader("some input")
					var out bytes.Buffer
					cmd.Stdout = &out
					err := cmd.Run()
					if err != nil {
						fmt.Printf("Run Errors: %s", err)
					}
					// fmt.Printf("AT: %s\n", godebug.LF())
					fmt.Printf("%s\n", out.String())
				}
			case <-quit:
				// fmt.Printf("AT: %s\n", godebug.LF())
				ticker.Stop()
				return
			}
		}
	}()

	// Watch file for changes -----------------------------------------------------------------------------
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		log.Fatal(err)
	}

	// fmt.Printf("AT: %s\n", godebug.LF())
	done := make(chan bool)

	// Process events
	go func() {
		for {
			// fmt.Printf("AT: %s\n", godebug.LF())
			select {
			case ev := <-watcher.Event:
				// fmt.Printf("AT: %s\n", godebug.LF())
				fmt.Printf("Event: %+v\n", ev) // log.Println("event:", ev)
				name := ev.Name
				isRen := ev.IsRename()
				fmt.Printf("Caught an event, %s\n", godebug.SVar(ev))

				setRunCmd(true)

				if isRen {
					err = watcher.Watch(name)
					if err != nil {
						fmt.Printf("Failed to set watch on %s, %s, -- will try again in 1/10 of second %s\n", name, err, godebug.LF())
						go func(watcher *fsnotify.Watcher, name string) {
							time.Sleep(100 * time.Millisecond)
							err := watcher.Watch(name)
							if err != nil {
								fmt.Printf("Failed to set watch on %s, %s, -- 2nd try%s\n", name, err, godebug.LF())
							} else {
								fmt.Printf("Success on 2nd try - watch on %s, %s\n", name, godebug.LF())
							}
						}(watcher, name)
					}

				}
			case err := <-watcher.Error:
				// fmt.Printf("AT: %s\n", godebug.LF())
				log.Println("error:", err)
			}
		}
		// fmt.Printf("AT: %s\n", godebug.LF())
	}()

	fmt.Printf("***************************************\n")
	fmt.Printf("* watching %s \n", flist)
	fmt.Printf("***************************************\n")
	for _, fn := range flist {
		// fmt.Printf("AT: %s\n", godebug.LF())
		if DirExists(fn) {
			var fns []string
			if !optsRecursive {
				fns, _ = GetFilenames(fn)
			} else {
				fns, _, _ = GetFilenamesRecrusive(fn)
			}
			for _, fn0 := range fns {
				err = watcher.Watch(fn0)
				if err != nil {
					fmt.Printf("Failed to set watch on %s, %s, %s\n", fn0, err, godebug.LF())
				}
			}
		} else {
			// fmt.Printf("AT: %s\n", godebug.LF())
			err = watcher.Watch(fn)
			if err != nil {
				fmt.Printf("Failed to set watch on %s, %s, %s\n", fn, err, godebug.LF())
			}
		}
		// fmt.Printf("AT: %s\n", godebug.LF())
	}
	// fmt.Printf("AT: %s\n", godebug.LF())

	<-done

	// fmt.Printf("AT: %s\n", godebug.LF())
	/* ... do stuff ... */
	watcher.Close()
}
Example #24
0
File: main.go Project: pdehaan/wmf
func main() {
	flags.ParseArgs(&opts, os.Args)

	// Configuration
	// defaults don't appear to work.
	if opts.ConfigFile == "" {
		opts.ConfigFile = "config.ini"
	}
	config := util.MzGetConfig(opts.ConfigFile)
	config["VERSION"] = VERSION
	if util.MzGetFlag(config, "aws.get_hostname") {
		if hostname, err := util.GetAWSPublicHostname(); err == nil {
			config["ws_hostname"] = hostname
		}
	}

	//TODO: Build out the partner cert pool if need be.
	// certpoo

	if opts.Profile != "" {
		log.Printf("Creating profile %s...\n", opts.Profile)
		f, err := os.Create(opts.Profile)
		if err != nil {
			log.Fatal("Profile creation failed:\n%s\n", err.Error())
			return
		}
		defer func() {
			log.Printf("Closing profile...\n")
			pprof.StopCPUProfile()
		}()
		pprof.StartCPUProfile(f)
	}
	if opts.MemProfile != "" {
		defer func() {
			profFile, err := os.Create(opts.MemProfile)
			if err != nil {
				log.Fatal("Memory Profile creation failed:\n%s\n", err.Error())
				return
			}
			pprof.WriteHeapProfile(profFile)
			profFile.Close()
		}()
	}

	runtime.GOMAXPROCS(runtime.NumCPU())
	logger := util.NewHekaLogger(config)
	store, err := storage.Open(config, logger)
	if err != nil {
		logger.Error("main", "FAIL", nil)
		return
	}
	handlers := wmf.NewHandler(config, logger, store)

	// Signal handler
	sigChan := make(chan os.Signal)
	signal.Notify(sigChan, syscall.SIGINT, syscall.SIGHUP, SIGUSR1)

	// Rest Config
	errChan := make(chan error)
	host := util.MzGet(config, "host", "localhost")
	port := util.MzGet(config, "port", "8080")

	var RESTMux *http.ServeMux = http.DefaultServeMux
	var WSMux *http.ServeMux = http.DefaultServeMux
	var verRoot = strings.SplitN(VERSION, ".", 2)[0]

	// REST calls
	// Device calls.
	RESTMux.HandleFunc(fmt.Sprintf("/%s/register/", verRoot),
		handlers.Register)
	RESTMux.HandleFunc(fmt.Sprintf("/%s/cmd/", verRoot),
		handlers.Cmd)
	// Web UI calls
	RESTMux.HandleFunc(fmt.Sprintf("/%s/queue/", verRoot),
		handlers.Queue)
	RESTMux.HandleFunc(fmt.Sprintf("/%s/state/", verRoot),
		handlers.State)
	RESTMux.HandleFunc("/static/",
		handlers.Static)
	RESTMux.HandleFunc("/metrics/",
		handlers.Metrics)
	// Operations call
	RESTMux.HandleFunc("/status/",
		handlers.Status)
	WSMux.Handle(fmt.Sprintf("/%s/ws/", verRoot),
		websocket.Handler(handlers.WSSocketHandler))
	// Handle root calls as webUI
	RESTMux.HandleFunc("/",
		handlers.Index)

	logger.Info("main", "startup...",
		util.Fields{"host": host, "port": port})

	go func() {
		errChan <- http.ListenAndServe(host+":"+port, nil)
	}()

	select {
	case err := <-errChan:
		if err != nil {
			panic("ListenAndServe: " + err.Error())
		}
	case <-sigChan:
		logger.Info("main", "Shutting down...", nil)
	}

}
Example #25
0
func main() {
	if _, err := flags.ParseArgs(&opts, os.Args); err != nil {
		log.Fatalf(err.Error())
		return
	}

	// Configuration
	// TODO: switch to regular go flag package
	// defaults don't appear to work.
	if opts.ConfigFile == "" {
		opts.ConfigFile = "config.ini"
	}

	config, err := util.ReadMzConfig(opts.ConfigFile)
	if err != nil {
		log.Fatalf("Could not read config file %s: %s", opts.ConfigFile, err.Error())
		return
	}

	fullVers := fmt.Sprintf("%s-%s", config.Get("VERSION", VERSION),
		getCodeVersion())
	config.Override("VERSION", fullVers)
	config.Override("SERVER", SERVER)
	config.Override("ddl.create", opts.Ddlcreate)
	config.Override("ddl.downgrade", opts.Ddldowngrade)
	if opts.LogFile != "" {
		config.Override("logger.output", opts.LogFile)
	}
	if opts.Ddlupgrade {
		config.SetDefaultFlag("ddl.upgrade", true)
	}
	if opts.Ddllog {
		config.SetDefaultFlag("ddl.log", true)
	}
	sock_secret, _ := util.GenUUID4()
	config.SetDefault("ws.socket_secret", sock_secret)

	// Rest Config
	errChan := make(chan error)
	host := config.Get("host", "localhost")
	port := config.Get("port", "8080")

	if config.GetFlag("aws.get_hostname") {
		if hostname, err := util.GetAWSPublicHostname(); err == nil {
			config.SetDefault("ws_hostname", hostname)
		}
		if port != "80" {
			config.SetDefault("ws_hostname", config.Get("ws_hostname", "")+":"+port)
		}
	}

	// Partner cert pool contains the various self-signed certs that
	// partners may require to access their servers (for Proprietary
	// wake mechanisms like UDP)
	// This would be where you collect the certs and store them into
	// the config map as something like:
	// config["partnerCertPool"] = self.loadCerts()

	if opts.Profile != "" {
		log.Printf("Creating profile %s...\n", opts.Profile)
		f, err := os.Create(opts.Profile)
		if err != nil {
			log.Fatal(fmt.Sprintf("Profile creation failed:\n%s\n",
				err.Error()))
			return
		}
		defer func() {
			log.Printf("Writing app profile...\n")
			pprof.StopCPUProfile()
		}()
		pprof.StartCPUProfile(f)
	}
	if opts.MemProfile != "" {
		defer func() {
			profFile, err := os.Create(opts.MemProfile)
			if err != nil {
				log.Fatal(fmt.Sprintf("Memory Profile creation failed:\n%s\n", err.Error()))
				return
			}
			log.Printf("Writing memory profile...\n")
			pprof.WriteHeapProfile(profFile)
			profFile.Close()
		}()
	}

	runtime.GOMAXPROCS(runtime.NumCPU())
	logger := util.NewLogger(config)
	metrics := util.NewMetrics(config.Get(
		"metrics.prefix",
		"wmf"), logger, config)
	if err != nil {
		logger.Error("main", "Unable to connect to database. Have you configured it yet?", nil)
		return
	}
	if hawkCount := config.Get("hawk.nonce_cache", "1000"); hawkCount != "1000" {
		count, err := strconv.ParseInt(hawkCount, 10, 32)
		if err != nil {
			log.Printf("Could not read hawk.nonce_cache, defaulting to 1000")
		} else {
			wmf.InitHawkNonces(count)
		}
	}
	handlers := wmf.NewHandler(config, logger, metrics)
	if handlers == nil {
		log.Fatalf("Could not start server. Please check config.ini")
	}

	// Signal handler
	sigChan := make(chan os.Signal)
	signal.Notify(sigChan, syscall.SIGINT, syscall.SIGHUP, syscall.SIGUSR1)

	var RESTMux = http.DefaultServeMux
	var WSMux = http.DefaultServeMux
	var verRoot = strings.SplitN(VERSION, ".", 2)[0]

	// REST calls

	RESTMux.HandleFunc(fmt.Sprintf("/%s/register/", verRoot),
		handlers.Register)
	RESTMux.HandleFunc(fmt.Sprintf("/%s/cmd/", verRoot),
		handlers.Cmd)
	// Web UI calls
	RESTMux.HandleFunc(fmt.Sprintf("/%s/queue/", verRoot),
		handlers.RestQueue)
	RESTMux.HandleFunc(fmt.Sprintf("/%s/state/", verRoot),
		handlers.State)
	RESTMux.HandleFunc(fmt.Sprintf("/%s/l10n/client.json", verRoot),
		handlers.Language)
	// Static files (served by nginx in production)
	if config.GetFlag("use_insecure_static") {
		RESTMux.HandleFunc("/bower_components/",
			handlers.Static)
		RESTMux.HandleFunc("/images/",
			handlers.Static)
		RESTMux.HandleFunc("/scripts/",
			handlers.Static)
		RESTMux.HandleFunc("/styles/",
			handlers.Static)
	}
	// Metrics
	RESTMux.HandleFunc("/metrics/",
		handlers.Metrics)
	// Operations call
	RESTMux.HandleFunc("/status/",
		handlers.Status)
	//Signin
	// set state nonce & check if valid at signin
	RESTMux.HandleFunc("/signin/",
		handlers.Signin)
	//Signout
	RESTMux.HandleFunc("/signout/",
		handlers.Signout)
	// Config option because there are other teams involved.
	auth := config.Get("fxa.redir_uri", "/oauth/")
	RESTMux.HandleFunc(auth, handlers.OAuthCallback)

	WSMux.Handle(fmt.Sprintf("/%s/ws/", verRoot),
		websocket.Handler(handlers.WSSocketHandler))
	// Handle root calls as webUI
	// Get a list of registered devices for the currently logged in user
	RESTMux.HandleFunc(fmt.Sprintf("/%s/devices/", verRoot),
		handlers.UserDevices)
	// Get an object describing the data for a user's device
	// e.g. http://host/0/data/0123deviceid
	RESTMux.HandleFunc(fmt.Sprintf("/%s/data/", verRoot),
		handlers.InitDataJson)
	RESTMux.HandleFunc(fmt.Sprintf("/%s/validate/", verRoot),
		handlers.Validate)
	RESTMux.HandleFunc("/",
		handlers.Index)

	logger.Info("main", "startup...",
		util.Fields{"host": host, "port": port, "version": fullVers})

	go func() {
		errChan <- http.ListenAndServe(host+":"+port, nil)
	}()

	select {
	case err := <-errChan:
		if err != nil {
			log.Fatalf("ListenAndServe: " + err.Error())
		}
	case <-sigChan:
		logger.Info("main", "Shutting down...", nil)
	}
}
Example #26
0
func main() {

	junk, err := flags.ParseArgs(&opts, os.Args)

	if len(junk) != 1 {
		fmt.Printf("Usage: Invalid arguments supplied, %s\n", junk)
		os.Exit(1)
	}
	if err != nil {
		os.Exit(1)
	}

	port = fmt.Sprintf("%d", opts.Port)
	if opts.HostIP != "localhost" {
		host_ip = opts.HostIP
	}

	server, err := socketio.NewServer(nil)
	if err != nil {
		log.Fatal(err)
	}
	server.On("connection", func(so socketio.Socket) {
		log.Println("on connection")
		so.Join("chat")
		so.On("chat message", func(msg string) {
			m := make(map[string]interface{})
			m["a"] = "你好" // hello there
			e := so.Emit("cn1111", m)
			//这个没有问题			// this is no problem
			fmt.Println("\n\n")

			b := make(map[string]string)
			b["u-a"] = "中文内容" //这个不能是中文		// this is chineese // this can not be chineese
			m["b-c"] = b
			e = so.Emit("cn2222", m)
			log.Println(e)

			log.Println("emit:", so.Emit("chat message", msg))
			so.BroadcastTo("chat", "chat message", msg)
		})
		so.On("t45", func(msg string) {
			err := so.Emit("r45", "Yep")
			if err != nil {
				fmt.Printf("Error: %s\n", err)
			}
		})
		so.On("registerForName", func(name, pass string) {
			b := ValidateUser(name, pass)
			// store the soketio.Socket in a global map
			UserMapLock.Lock()
			UserMap[name] = &UserInfo{
				User:       name,
				IsLoggedIn: b,
				So:         so,
			}
			UserMapLock.Unlock()
			if b {
				so.Emit("chat message", "logged in")
			} else {
				so.Emit("chat message", "invalid username/password (try bob/123 or jane/abc)")
			}
		})
		so.On("logout", func(name string) {
			UserMapLock.Lock()
			delete(UserMap, name)
			UserMapLock.Unlock()
			so.Emit("chat message", "bye now")
		})
		so.On("sendMessageTo", func(iAm, name string, message string) {
			fmt.Printf("sendMessage func, name = %v, message = %v", name, message)
			UserMapLock.RLock()
			defer UserMapLock.RUnlock()
			from, ok1 := UserMap[iAm]
			if !ok1 || !from.IsLoggedIn {
				so.Emit("error", "Error: you are not logged in.")
				return
			}
			dest, ok2 := UserMap[name]
			if !ok2 || !dest.IsLoggedIn {
				so.Emit("error", "Error: not logged in:"+name)
				return
			}
			dest.So.Emit("chat message", message)
		})
		so.On("disconnection", func() {
			// xyzzy - get "name" from so.Id() - use for auto/logout on disconnect - cleanup of global hash
			log.Println("on disconnect")
		})
	})
	server.On("error", func(so socketio.Socket, err error) {
		log.Println("error:", err)
	})

	// ------------------ Send periodic time notices to client -------------------------------------------------------------------
	ticker := time.NewTicker(10 * time.Second)
	quit := make(chan struct{})
	go func() {
		for {
			select {
			case <-ticker.C:
				// do stuff
				server.BroadcastTo("chat", "chat message", "I am alive")
				if u, ok := UserMap["bob"]; ok {
					u.So.Emit("chat message", "Hi Bob!")
				}
			case <-quit:
				ticker.Stop()
				return
			}
		}
	}()

	http.Handle("/socket.io/", server)
	http.Handle("/", http.FileServer(http.Dir("./asset")))
	fmt.Printf("Serving on port %s, brows to http://localhost:%s/\n", port, port)
	listen := fmt.Sprintf("%s:%s", host_ip, port)
	log.Fatal(http.ListenAndServe(listen, nil))
}