Пример #1
0
func setupLogger(logDir string) *log.Logger {
	var logger *log.Logger

	log.SetFlags(log.Ldate | log.Lmicroseconds)

	if logDir != "" {
		logFile := filepath.Join(logDir, "host.log")
		if err := os.MkdirAll(filepath.Dir(logFile), 0755); err != nil {
			log.Fatalf("could not not mkdir for logs: %s", err)
		}

		hostlog, err := os.OpenFile(logFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
		if err != nil {
			log.Fatal(err)
		}
		defer hostlog.Close()

		log.Printf("Logging to %s\n", logFile)
		log.SetOutput(io.MultiWriter(hostlog, os.Stdout))
		logger = log.New(io.MultiWriter(hostlog, os.Stderr), "", log.Flags())
	} else {
		logger = log.New(os.Stderr, "", log.Flags())
	}

	return logger
}
Пример #2
0
func log_debug(msg string, a ...interface{}) {
	if !debugging {
		return
	}
	defer log.SetFlags(log.Flags())
	log.SetFlags(log.Flags() | log.Lshortfile)
	msg = fmt.Sprintf(msg, a...)
	log.Output(2, msg)
}
Пример #3
0
// Init initializes flags and run all functions in initFunc.
func Init() {
	log.SetFlags(log.Lshortfile | log.Flags())
	flag.Parse()
	if !flag.Parsed() {
		log.Fatal("Unable to parse flags")
	}
	logger = log.New(os.Stderr, "", log.Lshortfile|log.Flags())
	AssertTrue(logger != nil)
	printVersionOnly()
	// Next, run all the init functions that have been added.
	for _, f := range initFunc {
		f()
	}
}
Пример #4
0
func SetAttribPointers(locations interface{}, vertexData interface{}, instanced bool) {
	attribs, _ := LocationMap(locations)
	Type := reflect.TypeOf(vertexData).Elem()
	stride := int(Type.Size())

	for i := 0; i < Type.NumField(); i++ {
		structElement := Type.Field(i)
		elementType := structElement.Type

		var size uint
		var typ gl.GLenum
		var kind reflect.Kind

		switch elementType.Kind() {
		case reflect.Array:
			size = uint(elementType.Len())
			kind = elementType.Elem().Kind()
		default:
			size = 1
			kind = elementType.Kind()
		}

		switch kind {
		case reflect.Float32:
			typ = gl.FLOAT
		case reflect.Float64:
			typ = gl.DOUBLE
		default:
			panic("not implemented yet")
		}

		offset := structElement.Offset

		Loc := attribs[structElement.Name]
		if Loc >= 0 {
			Loc.EnableArray()
			Loc.AttribPointer(size, typ, false, stride, offset)
			if instanced {
				Loc.AttribDivisor(1)
			}
			if log.Flags()&VERTEX_INFO_FLAG != 0 {
				log.Printf("%s: Loc: %d, size: %d, type: %d, stride: %d, offset: %d\n", structElement.Name, Loc, size, typ, stride, offset)
			}
		} else if log.Flags()&VERTEX_INFO_FLAG != 0 {
			log.Printf("%s: Loc: %d, !!!\n", structElement.Name, Loc)
		}
	}
}
Пример #5
0
func TestTripleDuplicates(t *testing.T) {
	t.Parallel()

	file, err := ioutil.TempFile(os.TempDir(), "triplestore.db")
	if err != nil {
		t.Fatal(err)
	}
	defer os.Remove(file.Name())
	db, err := NewTripleStore(file.Name(), log.New(os.Stdout, "", log.Flags()))
	if err != nil {
		t.Fatal(err)
	}

	db.Insert(testTriples)
	// Insert twice to ensure no duplicates.
	db.Insert(testTriples)

	info, err := db.Size()
	if err != nil {
		t.Fatal(err)
	}
	if info.Triples != uint64(len(testTriples)) {
		t.Errorf("Size() = %#v; not %d", info, len(testTriples))
	}
}
Пример #6
0
func main() {
	flag.DurationVar(&gBenchDur, "d", time.Millisecond, "duration for bench")

	var (
		localAddr  = flag.String("l", "", "local udp address, eg: ip:port")
		serverAddr = flag.String("h", "", "server udp address, eg: ip:port")
		concurent  = flag.Int("c", 1, "concurent client number")
	)
	flag.Parse()

	log.SetFlags(log.Flags() | log.Lshortfile)
	if len(*localAddr) == 0 || len(*serverAddr) == 0 {
		flag.Usage()
		return
	}
	server, err := net.ResolveUDPAddr("udp", *serverAddr)
	if err != nil {
		fmt.Printf("Resolve server addr %s failed: %v\n", *serverAddr, err)
		return
	}
	local, err := net.ResolveUDPAddr("udp", *localAddr)
	if err != nil {
		fmt.Printf("Resolve local addr %s failed: %v\n", *localAddr, err)
		return
	}

	firstPort := local.Port
	// 跳过监听失败的端口
	for p, n := 0, 0; n < *concurent; p++ {
		local.Port = firstPort + p
		socket, err := net.ListenUDP("udp", local)
		if err != nil {
			fmt.Printf("Listen on local addr %v failed: %v\n", local, err)
			continue
		}
		n++
		c := Client{
			Name:        "deviceName",
			ProduceTime: time.Now(),
			DeviceType:  0xFFFE,
			Sid:         make([]byte, 16),
			Socket:      socket,
			ServerAddr:  server,
			rch:         make(chan []byte, 128),
		}
		binary.LittleEndian.PutUint32(c.SN[11:15], uint32(n))
		binary.LittleEndian.PutUint32(c.MAC[3:7], uint32(n))
		log.Printf("Client started, mac: %v, sn: %v", hex.EncodeToString(c.MAC[:]), hex.EncodeToString(c.SN[:]))
		go c.Run()
	}
	c := make(chan os.Signal, 1)
	signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)

	for sig := range c {
		switch sig {
		case syscall.SIGINT, syscall.SIGTERM:
			return
		}
	}
}
Пример #7
0
func main() {
	var err error
	db, err = sql.Open("mysql", "root:123456@tcp(182.92.69.21:3305)/game_server?charset=utf8")
	db.SetMaxOpenConns(50)
	db.SetMaxIdleConns(50)
	defer db.Close()
	err = db.Ping()
	if err != nil {
		log.Fatal(err)
	}

	log.SetFlags(log.Flags() | log.Lshortfile)
	a.HandleConnect(handleConnect)
	a.HandleMessage(handleMessage)
	a.HandleDisconnect(handleDisconnect)

	ch := make(chan os.Signal)
	signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
	go a.Start()
	go Handle()
	go pingHandle()
	<-ch
	hql.Truncate_server(db)
	hql.Truncate_platform(db)
	a.Stop(shutdown)
	wg.Wait()

}
Пример #8
0
func main() {
	log.SetFlags(log.Flags() | log.Lshortfile)
	parsed, err := docopt.Parse(whitespace.CleanWS(`
	Usage:
	  docker_labels [options] <image-name>

	Options:
	  --insecure  makes the connection to e.g. a self-signed registry
	`), nil, true, "", false)

	if err != nil {
		log.Fatal(err)
	}

	imageName := parsed["<image-name>"].(string)
	client := docker_registry.NewClient()
	if _, ok := parsed["--insecure"]; ok {
		client.BecomeFoolishlyTrusting()
	}

	labels, err := client.LabelsForImageName(imageName)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Found %d labels:\n", len(labels))
	for key, value := range labels {
		fmt.Printf("%s: %s\n", key, value)
	}
}
Пример #9
0
func main() {
	log.SetFlags(log.Flags() | log.Llongfile)

	//recv := &chromebus.ChromebusRecordStdinReceiver{}
	//str, _ := recv.GetRecord()
	//log.Printf("%s", str)
	//str, _ = recv.GetRecord()
	//log.Printf("%s", str)
	flag.Parse()
	flag.VisitAll(defFlags)
	if !serverMode {
		chromebus.EnvSetup()
	}
	var e *chromebus.Engine
	if pluginsDefined {
		e = chromebus.CreateEngine(plugins, port)
	} else {
		e = chromebus.CreateEngine(nil, port)
	}
	go func() {
		e.Start()
	}()
	signalChannel := make(chan os.Signal, 1)
	signal.Notify(signalChannel, os.Interrupt, os.Kill)
	<-signalChannel
	e.CleanUp()

	//rcv := ChromebusRecordStdinReceiver{}
	//exec.Command("date")
}
Пример #10
0
func main() {
	log.SetFlags(log.Flags() | log.Lshortfile)
	parsed, err := docopt.Parse(`Usage: cert_san <cert-path>`, nil, true, "", false)

	if err != nil {
		log.Fatal(err)
	}

	certPath := parsed["<cert-path>"].(string)

	certFile, err := os.Open(certPath)
	if err != nil {
		log.Fatal(err)
	}

	certBuf := bytes.Buffer{}
	_, err = certBuf.ReadFrom(certFile)
	if err != nil {
		log.Fatal(err)
	}

	log.Print("\n", certBuf.String())
	block, _ := pem.Decode(certBuf.Bytes())

	cert, err := x509.ParseCertificate(block.Bytes)
	if err != nil {
		log.Fatal(err)
	}

	log.Printf("Cert good for addresses: %+v", cert.IPAddresses)
}
Пример #11
0
func main() {

	r := Rectangle{length: 5, width: 3}
	fmt.Println("Rectangle r details are: ", r)
	fmt.Println("Rectangle r's area is: ", r.Area())

	s := Shaper(r)
	fmt.Println("Area of the Shape r is: ", s.Area())
	fmt.Println("Area of the Shape r is: ", s.Shit())

	return

	cfgFile := "file.txt"

	f, err := os.OpenFile(cfgFile, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666) // For read access.
	if err != nil {
		checkError(err)
	}

	//	var l int
	myLog := log.New(f, "PREFIXIO ", log.Lshortfile|log.Ldate|log.Ltime)
	//	l, err = f.WriteString("HELLO THERE n");
	//	fmt.Printf("length is :%d\n", l);
	if err != nil {
		checkError2(err)
	}
	myLog.Println("from logger")
	//myFileAppendLine(cfgFile, "HELLO THERE \n");

	fmt.Printf("Flags:%q   Prefix:%q\n", log.Flags(), log.Prefix())
	os.Exit(0)
}
Пример #12
0
func init() {
	log.SetFlags(log.Flags() | log.Lshortfile)
	bytes, err := ioutil.ReadFile("config.conf")
	e(err, true)
	str := string(bytes)
	lines := strings.Split(str, "\n")
	reg, err := regexp.Compile(`\s+`)
	e(err, true)
	for num, line := range lines {
		if line == "" {
			continue
		}
		if strings.HasPrefix(line, "#") {
			continue
		}
		fields := reg.Split(line, -1)
		if len(fields) != 2 {
			log.Printf("Line %d is not match the config format.", num+1)
			continue
		}
		dbname := fields[0]
		dburi := fields[1]
		DBS[dbname] = dburi
		dbs[dbname] = init_db(dburi)
	}
}
Пример #13
0
// Setup registers all server handlers.
func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	log.SetFlags(log.Flags() | log.Lshortfile)
	flag.Parse()

	s, err := newServer()
	if err != nil {
		log.Fatal(err)
	}
	defer s.graph.Close()

	fs := http.FileServer(http.Dir("."))
	http.Handle("/static/", fs)

	http.HandleFunc("/", handleIndex)
	http.HandleFunc("/api/v1/recommendation", s.handleRecommendation)

	log.Printf("Serving on :%s...", *port)

	err = http.ListenAndServe("0.0.0.0:"+*port, nil)
	if err != nil {
		log.Println(err)
	}
	log.Println("Server on 6060 stopped")

	os.Exit(0)

}
Пример #14
0
// NewServer creates a new server with routing information. If log is nil, stdout is used.
func NewServer(logger *log.Logger, port int) (*Server, error) {
	if logger == nil {
		logger = log.New(os.Stdout, "", log.Flags())
	}
	s := &Server{
		Logger:   logger,
		Port:     port,
		Peers:    make(map[string]*Conn),
		handlers: make(map[string]protocolHandler),
	}

	s.listeningWG.Add(1)

	s.IP = getHost()

	s.listener = &httpListener{
		accept: make(chan *httpConn, 10),
	}

	s.initHTTPRouting()

	// Handlers
	s.Handle("Handshake", s.handleHandshake)
	s.Handle("PeerRequest", s.handlePeerRequest)
	s.Handle("PeerNotify", s.handlePeerNotify)

	return s, nil
}
Пример #15
0
func TestModifyScale(t *testing.T) {
	log.SetFlags(log.Flags() | log.Lshortfile)
	assert := assert.New(t)
	mods := make(chan *sous.DeployablePair, 1)
	errs := make(chan error, 10)

	pair := baseDeployablePair()
	pair.Prior.Deployment.DeployConfig.NumInstances = 12
	pair.Post.Deployment.DeployConfig.NumInstances = 24

	client := sous.NewDummyRectificationClient()

	deployer := NewDeployer(client)

	mods <- pair
	close(mods)
	deployer.RectifyModifies(mods, errs)
	close(errs)

	for e := range errs {
		t.Error(e)
	}

	assert.Len(client.Deployed, 0)
	if assert.Len(client.Created, 1) {
		assert.Equal(24, client.Created[0].Count)
	}
}
Пример #16
0
func main() {
	var dumpConf bool
	var confFile string

	flag.BoolVar(&dumpConf, "dumpconf", false, "dump the default configuration file")
	flag.StringVar(&confFile, "conf", "", "use this alternative configuration file")
	flag.Parse()

	stdoutLogger = log.New(os.Stderr, "", log.Flags())

	if dumpConf {
		dumpDefaultConf()
		return
	}

	rand.Seed(time.Now().Unix())

	if confFile != "" {
		setConf(confFile)
	}

	if conf.RealIP {
		goji.Insert(middleware.RealIP, middleware.Logger)
	}

	goji.Get("/", root)
	goji.Get("/:id", getPaste)
	goji.Post("/", createPaste)
	goji.Serve()
}
Пример #17
0
func TestStkErr(t *testing.T) {
	//Log automatically writes to Stderr
	//If not using official log, simply pass in os.Stderr as an io.Writer
	//to make it work
	fmt.Println("Const os.Stderr", os.Stderr)
	fmt.Println("Hey", log.Flags())
}
Пример #18
0
// Capture creates a new *Logger instance with an internal buffer. The prefix
// and flags default to the values of log.Prefix() and log.Flags(), respectively.
// This function is meant to be called from test code. See the godoc for the
// Logger struct for details.
func Capture() *Logger {
	out := new(bytes.Buffer)
	return &Logger{
		Log:    out,
		Logger: log.New(out, log.Prefix(), log.Flags()),
	}
}
Пример #19
0
func init() {
	// Set up builtin middlewarez
	OnBeforeNotify(httpRequestMiddleware)

	// Default configuration
	Config.update(&Configuration{
		APIKey:        "",
		Endpoint:      "https://notify.bugsnag.com/",
		Hostname:      "",
		AppVersion:    "",
		ReleaseStage:  "",
		ParamsFilters: []string{"password", "secret"},
		// * for app-engine
		ProjectPackages:     []string{"main*"},
		NotifyReleaseStages: nil,
		Logger:              log.New(os.Stdout, log.Prefix(), log.Flags()),
		PanicHandler:        defaultPanicHandler,
		Transport:           http.DefaultTransport,
	})

	hostname, err := os.Hostname()
	if err == nil {
		Config.Hostname = hostname
	}
}
Пример #20
0
func main() {
	log.Flags()
	log.SetFlags(0)

	// parse csv
	records := parse.Parse("../../../resources/table.csv")

	// parse template
	tpl, err := template.ParseFiles("hw.gohtml")
	if err != nil {
		log.Fatalln(err)
	}

	// function
	http.HandleFunc("/", func(res http.ResponseWriter, req *http.Request) {
		// execute template
		err = tpl.Execute(res, records)
		if err != nil {
			log.Fatalln(err)
		}
	})

	// create server
	http.ListenAndServe(":9000", nil)
}
Пример #21
0
func init() {
	log.SetFlags(log.Flags() | log.Lmicroseconds)

	http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir(configs.ServerRoot.Join("css").S()))))
	http.Handle("/js/", http.StripPrefix("/js/", http.FileServer(http.Dir(configs.ServerRoot.Join("js").S()))))
	http.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir(configs.ServerRoot.Join("images").S()))))
	http.Handle("/img/", http.StripPrefix("/img/", http.FileServer(http.Dir(configs.ServerRoot.Join("images").S()))))
	http.Handle("/robots.txt", http.FileServer(http.Dir(configs.ServerRoot.Join("static").S())))
	http.Handle("/clippy.swf", http.FileServer(http.Dir(configs.ServerRoot.Join("static").S())))

	http.HandleFunc("/add", pageAdd)
	http.HandleFunc("/search", pageSearch)
	http.HandleFunc("/view", pageView)
	http.HandleFunc("/tops", pageTops)
	http.HandleFunc("/about", staticPage("about.html"))
	http.HandleFunc("/infoapi", staticPage("infoapi.html"))
	http.HandleFunc("/api", pageApi)
	http.HandleFunc("/loadtemplates", pageLoadTemplate)
	http.HandleFunc("/badge", pageBadge)
	http.HandleFunc("/badgepage", pageBadgePage)
	http.HandleFunc("/crawlhistory", pageCrawlHistory)
	bi.HandleRequest(configs.BiWebPath)

	http.HandleFunc("/", pageRoot)
}
Пример #22
0
func main() {
	log.SetFlags(log.Flags() | log.Lshortfile)
	flag.Parse()
	metaInfo, err := metainfo.LoadFromFile(*torrentPath)
	if err != nil {
		log.Fatal(err)
	}
	mMapSpan := &mmap_span.MMapSpan{}
	if len(metaInfo.Info.Files) > 0 {
		for _, file := range metaInfo.Info.Files {
			filename := filepath.Join(append([]string{*dataPath, metaInfo.Info.Name}, file.Path...)...)
			goMMap := fileToMmap(filename, file.Length)
			mMapSpan.Append(goMMap)
		}
		log.Println(len(metaInfo.Info.Files))
	} else {
		goMMap := fileToMmap(*dataPath, metaInfo.Info.Length)
		mMapSpan.Append(goMMap)
	}
	log.Println(mMapSpan.Size())
	log.Println(len(metaInfo.Info.Pieces))
	info := metaInfo.Info
	for i := range iter.N(metaInfo.Info.NumPieces()) {
		p := info.Piece(i)
		hash := sha1.New()
		_, err := io.Copy(hash, io.NewSectionReader(mMapSpan, p.Offset(), p.Length()))
		if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("%d: %x: %v\n", i, p.Hash(), bytes.Equal(hash.Sum(nil), p.Hash().Bytes()))
	}
}
Пример #23
0
func init() {
	bind.WithFlag()
	if fl := log.Flags(); fl&log.Ltime != 0 {
		log.SetFlags(fl | log.Lmicroseconds)
	}
	graceful.DoubleKickWindow(2 * time.Second)
}
Пример #24
0
func main() {
	log.SetFlags(log.Flags() | log.Lshortfile)

	c := &gorpc.Client{
		// TCP address of the server.
		//		Addr: "127.0.0.1:12345",
		Addr: "10.10.18.97:12345",
	}
	c.Start()

	// All client methods issuing RPCs are thread-safe and goroutine-safe,
	// i.e. it is safe to call them from multiple concurrently running goroutines.
	resp, err := c.Call("foobar")
	if err != nil {
		log.Fatalf("Error when sending request to server: %s", err)
	}
	log.Println(resp)

	for i := 0; true; i++ {
		time.Sleep(2 * time.Second)
		person := comm.Person{
			No:   i,
			Name: "张三",
			Age:  14,
		}

		resp, err = c.Call(person)
		if err != nil {
			log.Fatalf("Error when sending request to server: %s", err)
		}

		log.Println(resp)
	}
}
Пример #25
0
func LogNoTime() {
	logLock.RLock()
	defer logLock.RUnlock()
	//Disable timestamp for default logger, this may be used by other packages
	log.SetFlags(log.Flags() &^ (log.Ldate | log.Ltime | log.Lmicroseconds))
	logNoTime = true
}
Пример #26
0
func (s *MainSuite) Test_initLog_SetsLogFlagsIfDebugging(c *C) {
	log.SetFlags(0)
	*config.DebugFlag = true
	initLog()
	c.Assert(log.Flags(), Equals, log.Ldate|log.Ltime|log.Llongfile)
	c.Assert(log.Prefix(), Equals, "[CoyIM] ")
}
Пример #27
0
func main() {
	log.SetFlags(log.Flags() | log.Lshortfile)

	s := gorpc.Server{
		// Accept clients on this TCP address.
		Addr: ":12345",
		// Echo handler - just return back the message we received from the client
		Handler: func(clientAddr string, request interface{}) interface{} {
			log.Printf("Obtained request %+v from the client %s\n", request, clientAddr)

			switch request.(type) {
			case string:
				return request
			case comm.Person:
				person, _ := request.(comm.Person)
				return comm.Student{
					Person: person,
					Grade:  "高三",
					Class:  "3班",
					School: "临湘二中",
				}
			}

			return "ERROR"
		},
	}

	if err := s.Serve(); err != nil {
		log.Fatalf("Cannot start rpc server: %s", err)
	}
}
// Serve starts Goji using reasonable defaults.
func Serve() {
	if !flag.Parsed() {
		flag.Parse()
	}

	log.SetFlags(log.Flags() | log.Lmicroseconds)

	// Install our handler at the root of the standard net/http default mux.
	// This allows packages like expvar to continue working as expected.
	http.Handle("/", DefaultMux)

	listener := bind.Default()
	log.Println("Starting Goji on", listener.Addr())

	graceful.HandleSignals()
	bind.Ready()

	err := graceful.Serve(listener, http.DefaultServeMux)

	if err != nil {
		log.Fatal(err)
	}

	graceful.Wait()
}
Пример #29
0
// Mount the file system based on the supplied arguments, returning a
// fuse.MountedFileSystem that can be joined to wait for unmounting.
func mount(
	ctx context.Context,
	bucketName string,
	mountPoint string,
	flags *FlagStorage) (mfs *fuse.MountedFileSystem, err error) {

	// Choose UID and GID.
	uid, gid, err := MyUserAndGroup()
	if err != nil {
		err = fmt.Errorf("MyUserAndGroup: %v", err)
		return
	}

	if int32(flags.Uid) == -1 {
		flags.Uid = uid
	}

	if int32(flags.Gid) == -1 {
		flags.Gid = gid
	}

	awsConfig := &aws.Config{
		Region: aws.String("us-west-2"),
		//LogLevel: aws.LogLevel(aws.LogDebug),
	}
	if len(flags.Endpoint) > 0 {
		awsConfig.Endpoint = &flags.Endpoint
	}
	if flags.UsePathRequest {
		awsConfig.S3ForcePathStyle = aws.Bool(true)
	}

	goofys := NewGoofys(bucketName, awsConfig, flags)
	if goofys == nil {
		err = fmt.Errorf("Mount: initialization failed")
		return
	}
	server := fuseutil.NewFileSystemServer(goofys)

	// Mount the file system.
	mountCfg := &fuse.MountConfig{
		FSName:                  bucketName,
		Options:                 flags.MountOptions,
		ErrorLogger:             log.New(os.Stderr, "fuse: ", log.Flags()),
		DisableWritebackCaching: true,
	}

	if flags.DebugFuse {
		mountCfg.DebugLogger = log.New(os.Stderr, "fuse_debug: ", 0)
	}

	mfs, err = fuse.Mount(mountPoint, server, mountCfg)
	if err != nil {
		err = fmt.Errorf("Mount: %v", err)
		return
	}

	return
}
Пример #30
0
func init() {
	// Set log format.
	f := log.Flags()
	log.SetFlags(f | log.Llongfile)

	// Initialisations.
	nameRegexp = regexp.MustCompile("^[a-z][a-z0-9_]*[a-z0-9]$")
}