示例#1
0
文件: main.go 项目: elimisteve/tsuru
func main() {
	gnuflag.Parse(true)
	name := cmd.ExtractProgramName(os.Args[0])
	manager := buildManager(name)
	args := gnuflag.Args()
	manager.Run(args)
}
示例#2
0
func main() {
	t0 := time.Now()
	conf := config.Config{}
	conf.MusicDir = flag.String("music-dir", "/music", "Music dir")
	conf.Port = flag.Int("port", 8080, "Pickup port")
	conf.MpdAddress = flag.String("mpd-address", "localhost:6600", "MPD address")
	conf.MpdPassword = flag.String("mpd-password", "", "MPD Password")

	flag.Parse(true)

	log.Printf("Mpd address: '%s'  password: '******'\n", *conf.MpdAddress,
		*conf.MpdPassword)

	plyr, err := player.NewMpdPlayer(&conf)
	if err != nil {
		log.Fatalln("Failed to initialize mpd player", err)
	}
	music, err := plyr.GetCollection()
	if err != nil {
		log.Fatalln("Failed to retrieve collection", err)
	}
	log.Printf("Player with %d categories initialized in %v\n", len(music.Categories), time.Since(t0))

	serve(&conf, &plyr)
}
示例#3
0
// main
func main() {
	//log.Printf("num cpus: %v", runtime.NumCPU())
	runtime.GOMAXPROCS(runtime.NumCPU())

	gnuflag.Usage = usage

	gnuflag.StringVar(&webroot, "r", "", "root directory for webserving")
	gnuflag.StringVar(&webport, "p", webportDefault, "listening port")

	gnuflag.Parse(true)

	if webroot == "" {
		usage()
		os.Exit(1)
	}

	e := webrootCheck()
	if e != nil {
		errorExit(fmt.Sprintf("%s: %v", webroot, e), 2)
	}

	userManager := NewUserManager()
	userManager.Start()
	connectionManager := connectionmanager.New()
	connectionManager.SetActive(true)

	log.Println("Running server")

	go runWebServer(connectionManager, userManager)

	// console
	fmt.Scanln()
}
示例#4
0
func main() {
	flag.Parse(true)
	if err := main0(); err != nil {
		fmt.Fprintf(os.Stderr, "%s\n", err)
		os.Exit(1)
	}
}
示例#5
0
func main() {
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "usage: juju-stateservers machine-id...\n")
		flag.PrintDefaults()
		os.Exit(2)
	}
	flag.Parse(true)
	if err := setStateServers(flag.Args()); err != nil {
		fmt.Fprintf(os.Stderr, "cannot set state servers: %v\n", err)
		os.Exit(1)
	}
}
// Main
func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	/*
			connectionCount = 200
			minDelay = 5000 // ms
			maxDelay = 20000
		connectionCount = 20
		minDelay = 1500 // ms
		maxDelay = 4000
	*/

	gnuflag.Usage = usage

	gnuflag.IntVar(&connectionCount, "c", 20, "number of simultaneous bots to run")
	gnuflag.IntVar(&minDelay, "n", 1500, "minimum delay time between chats (ms)")
	gnuflag.IntVar(&maxDelay, "x", 4000, "maximum delay time between chats (ms)")

	gnuflag.Parse(true)

	if connectionCount < 1 || minDelay < 0 || maxDelay < 0 {
		usage()
		os.Exit(1)
	}

	if minDelay > maxDelay {
		t := minDelay
		minDelay = maxDelay
		maxDelay = t
	}

	for i := 0; i < connectionCount; i++ {
		go robot()
	}

	fmt.Printf("Hit return to quit")
	fmt.Scanln()
}
示例#7
0
文件: main.go 项目: hoffoo/pickup
func main() {
	var action = flag.String("action", "serve", "Action to perform (serve|refresh)")
	conf := config.Config{}
	conf.MusicDir = flag.String("music-dir", "/music", "Music dir")
	conf.Port = flag.Int("port", 8080, "Pickup port")
	conf.MpdAddress = flag.String("mpd-address", "localhost:6600", "MPD address")
	conf.MpdPassword = flag.String("mpd-password", "", "MPD Password")

	var query = flag.String("query", "", "Search query")
	flag.Parse(true)

	fmt.Println("Action is:", *action)
	fmt.Printf("Mpd address: '%s'  password: '******'\n", *conf.MpdAddress,
		*conf.MpdPassword)

	//collection := loadOrRefresh(*conf.MusicDir)
	music, err := model.RefreshMpd(&conf)
	if err != nil {
		log.Fatalf("Couldn't get files from mpd: \n%s\n", err)
	}

	switch *action {
	case "stats":
		stats(music.Categories[0])
	case "search":
		search(music, *query)
	case "serve":
		serve(&conf, music)
	case "test-playback":
		testPlayback(&conf, music)
	case "refresh":
		os.Exit(0)
	default:
		fmt.Println("Unknown action", *action)
	}
}
func main() {
	var track_ids []int
	track_etags := map[string]string{}

	// capture ctrl+c and stop CPU profiler
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	signal.Notify(c, syscall.SIGQUIT)
	signal.Notify(c, syscall.SIGTERM)
	go func() {
		<-c
		exit_and_output_stats()
	}()

	ok := true

	output_welcome()

	flag.Parse(true)
	if *helpFlag {
		output_help()
	} else {

		// If track flag is present, append listed track_ids
		if *tracksFlag != "" {
			track_ids = append(track_ids, track_ids_from_tracks_flag()...)
		}

		// If file flag is present, append track_ids from file
		if *fileFlag != "" {
			track_ids = append(track_ids, track_ids_from_file_flag()...)
		}

		if ok {
			var track_id int

			if len(track_ids) == 0 {
				for {
					fmt.Printf("Enter a track_id: ")
					fmt.Scanf("%d", &track_id)

					if track_id == 0 {
						track_id = 816296
					}
					track_ids = append(track_ids, track_id)
					fmt.Printf("Add more tracks? [y/n] ")
					if !confirm.AskForConfirmation() {
						break
					}
				}
			}

			fmt.Println("Fetching all the track details...")

			for _, element := range track_ids {
				tracks = append(tracks, get_track_info(element).Tracks[0])
			}

			fmt.Println("Track list built.")

			fmt.Println(output_tracklist(tracks))

			fmt.Printf("Is this correct? [y/n] ")
			if confirm.AskForConfirmation() {
				for {
					for _, track := range tracks {
						if track.Duration == "" {
							track.Duration = "00:04:42"
						}

						fmt.Printf("Playing %s-%s\n", track.ArtistTitle, track.Title)

						if track_etags[track.URL128] == "" {
							url_headers := http_head(track.URL128)
							track_etags[track.URL128] = url_headers["Etag"][0]
						}

						hit_mp3_url(track.URL128, track_etags[track.URL128])
						hit_track_play(track.ID)
						playedTracksCount[track.ID]++
						sleep_for_track_length(track.Duration)
					}
				}
			} else {
				fmt.Println()
				fmt.Println("Exiting unearthd-bumpr...")
				fmt.Println()
				os.Exit(2)
			}
		}

	}
}
示例#9
0
func main() {

	flag.Parse(true)
	showWelcomeMessage()
	if *aboutFlag == true {
		showAboutMessage()
		os.Exit(0)
	}

	var tracklist []Track
	tracklistFileName := ""

	if *trackListFlag != "" {
		tracklistFileName = *trackListFlag
		tracklist = parseTracklist(trackListFlag)
	} else {
		if len(os.Args) > 1 {
			if os.Args[1][0:2] != "--" {
				tracklistFileName = string(os.Args[1])
				tracklist = parseTracklist(&tracklistFileName)
			} else {
				term.OutputError("Please provide a tracklist to parse")
				os.Exit(1)
			}
		} else {
			term.OutputError("Please provide a tracklist to parse")
			os.Exit(1)
		}
	}

	if len(tracklist) < 9 {
		term.OutputError("Not enough tracks in tracklist")
		os.Exit(1)
	}

	overlay_filename := ""
	if *overlayFlag != "" {
		overlay_filename = *overlayFlag
	}

	output_filename := strings.Replace(tracklistFileName, ".txt", ".jpg", -1)

	if *outputFileFlag != "" {
		output_filename = *outputFileFlag
	} else {
		if len(os.Args) > 2 {
			if os.Args[2][0:2] != "--" && os.Args[2] != "" {
				output_filename = string(os.Args[2])
			}
		}
	}

	artists := countArtists(tracklist)
	sortedArtists := sortMapByValue(artists)

	selection := sortedArtists[:9]

	db, err := bolt.Open(DATABASE_FILENAME, 0600, nil)
	if err != nil {
		term.OutputError(err.Error())
		os.Exit(2)
	}
	defer db.Close()

	db.Update(func(tx *bolt.Tx) error {
		_, err := tx.CreateBucketIfNotExists(DATABASE_BUCKET)
		if err != nil {
			return fmt.Errorf("create bucket: %s", err)
		}
		return nil
	})

	for i, _ := range selection {
		j := 0
		for !GetCover(db, i, &selection[i]) {
			replacement := sortedArtists[9+i+j]
			term.OutputError(fmt.Sprintf("Replacing with %s", replacement.Artist))
			selection[i] = replacement
			j++
		}
	}

	createImage(selection, output_filename, overlay_filename)
}
示例#10
0
func main() {
	foreground := flag.Bool("f", false, "Run application foreground, don't daemonize")
	config_path := flag.String("config", "config.json", "Configuration file path")
	pid_path := flag.String("pid", "/var/run/ng_backend.pid", "PID file path")
	flag.Parse(false)
	init_config(*config_path)
	d_config := get_daemon_config()
	state_config := get_state_config()
	metric_config := get_metric_config()
	graph_config := get_graph_config()

	if !*foreground {
		cntxt := &daemon.Context{
			PidFileName: *pid_path,
			PidFilePerm: 0644,
			LogFileName: d_config.GetString("log_file"),
			LogFilePerm: 0640,
			WorkDir:     "./",
			Umask:       027,
			Args:        []string{},
		}

		d, err := cntxt.Reborn()
		if err != nil {
			log.Fatalln(err)
		}
		if d != nil {
			return
		}
		defer cntxt.Release()
	}

	log.Println("Starting NetAssist NetGraphz2...")

	log.Printf("Create memory metric storage with capacity of %d records per metric\n", metric_config.GetInt("mem_storage.capacity"))

	metric_store := metric.NewMemoryStorage(metric_config.GetInt("mem_storage.capacity"))
	status_srv := state.NewStatusService(state.NewMemoryStateCache(), time.Duration(state_config.GetInt("cache.ttl"))*time.Millisecond)
	graph_store := graph.NewNeoGraphStorage(graph_config.GetString("url"))

	icinga_config := state.IcingaLiveStatusConfig{}
	icinga_config.HostName = state_config.GetString("icinga.host")
	icinga_config.Port = uint16(state_config.GetInt("icinga.port"))
	icinga_config.UseUnixSocket = state_config.GetBool("icinga.use_unix_socket")
	icinga_config.UnixSocket = state_config.GetString("icinga.unix_socket")
	icinga_config.TimeoutEnable = state_config.GetBool("icinga.timeout_enabled")
	icinga_config.Timeout = time.Duration(state_config.GetInt("icinga.timeout")) * time.Millisecond

	icinga_source := state.NewIcingaLiveStateSource(icinga_config)
	status_srv.AddSource(icinga_source)

	lis, err := net.Listen("tcp", net.JoinHostPort(d_config.GetString("rpc_host"), fmt.Sprintf("%d", d_config.GetInt("rpc_port"))))
	if err != nil {
		log.Printf("failed to listen: %v", err)
	}
	var opts []grpc.ServerOption
	grpcServer := grpc.NewServer(opts...)
	rpc.RegisterBackendServer(grpcServer, rpc_server.NewRPCServer(graph_store, status_srv, metric_store))

	go func() {
		log.Printf("gRPC server starting on %s:%d\n", d_config.GetString("rpc_host"), d_config.GetInt("rpc_port"))
		err := grpcServer.Serve(lis)
		if err != nil {
			log.Fatalf("Error during listening: %v\n", err)
		}
	}()

	log.Printf("Starting collectd listener on %s:%d\n", metric_config.GetString("collectd.host"), metric_config.GetInt("collectd.port"))

	source := metric.NewCollectdMetricSource(metric_config.GetString("collectd.host"), uint16(metric_config.GetInt("collectd.port")), metric_config.GetBool("collectd.filter_enable"), metric_config.GetStringSlice("collectd.filter_types"))
	source.AddStorage(metric_store)
	log.Println("Collecting collectd metrics")
	source.Collect()
}
示例#11
0
func main() {
	flag.Parse(true)

	showWelcomeMessage()
	if *aboutFlag == true {
		showAboutMessage()
		os.Exit(0)
	}

	setupApp()
	loadConfig()

	CURRENT_USER = fetchMe(configuration.ACCESS_TOKEN)

	var tracklist []mixcloud.Track

	if *configFlag == true {
		createConfig()
	}

	if *trackListFlag != "" {
		tracklist = parseVirtualDJTrackList(trackListFlag)
	}

	if *fileFlag == "" {
		OutputError("You must pass a file to upload, use --file or see --help.\n Exiting.")
		os.Exit(2)
	}

	b := &bytes.Buffer{}

	writer := multipart.NewWriter(b)

	cast_name, cast_desc, tags_arr := GetBasicInput()

	BuildBasicHTTPWriter(writer, cast_name, cast_desc, tags_arr, tracklist)
	AddPremiumToHTTPWriter(writer)

	// Add MP3
	if *fileFlag != "" {
		loadFileToWriter(*fileFlag, "mp3", writer)
	}

	// Add cover image
	if *coverFlag != "" {
		loadFileToWriter(*coverFlag, "picture", writer)
	}

	writer.Close()

	// bufReader := bufio.NewReader(b)
	// for line, _, err := bufReader.ReadLine(); err != io.EOF; line, _, err = bufReader.ReadLine() {
	// 	OutputMessage(string(line) + "\n")
	// }

	request, bar := HttpUploadRequest(b, writer)

	bar.Empty = term.Red + "-" + term.Reset
	bar.Current = term.Green + "=" + term.Reset
	client := &http.Client{}
	OutputMessage("\n\n")
	STD_OUT.Flush()
	bar.Start()
	resp, err := client.Do(request)
	if err != nil {
		OutputError("Error: " + err.Error())
		os.Exit(2)
	}
	bar.Finish()

	var Response *mixcloud.Response = new(mixcloud.Response)

	error := json.NewDecoder(resp.Body).Decode(&Response)

	resp.Body.Close()
	if error != nil {
		OutputError("Error decoding response from API - " + error.Error())
		os.Exit(2)
	}

	if handleJSONResponse(*Response) {
		printTracklist(tracklist)
	} else {
		os.Exit(2)
	}
}