// Returns a singleton instance of API, intialised with an empty DB containing a
// single user and a silent version of ClassicMartini
func getTestApi() API {
	if test_api != nil {
		return test_api
	}

	// Set Log level here. This should only be called once, and near the start
	// of the test run
	if !*verboseMartini {
		log.SetLevel(log.ErrorLevel)
	} else {
		log.SetLevel(log.DebugLevel)
	}

	db := getTestDb()
	a := New(Options{JwtKey: "RandomString", Db: db, Martini: getSilentMartini()})

	a.AddDefaultRoutes(&PrivateWidget{}, RouteOptions{Authenticate: true})
	a.AddDefaultRoutes(&Widget{})
	a.AddDefaultRoutes(&VerifiedWidget{})
	a.AddDefaultRoutes(&Widget{}, RouteOptions{UriModelName: "other_widgets"})

	a.AddDefaultRoutes(&User{})
	a.SetAuth(&User{}, "/auth")

	test_api = a
	return a
}
Exemple #2
0
func main() {
	config, err := core.ParseConfig("./config.yaml")
	if err != nil {
		logrus.Errorf("Failed to parse configuration: %s", err)
		return
	}

	switch core.Global.Logging {
	case "debug":
		logrus.SetLevel(logrus.DebugLevel)
	case "info":
		logrus.SetLevel(logrus.InfoLevel)
	case "warn":
		logrus.SetLevel(logrus.WarnLevel)
	case "error":
		logrus.SetLevel(logrus.ErrorLevel)
	default:
		logrus.SetLevel(logrus.InfoLevel)
		logrus.Warnf("Home: invalid log level supplied: '%s'", core.Global.Logging)
	}

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	go func() {
		for sig := range c {
			_ = sig
			eventbus.EventBus.Publish(eventbus.Event{
				Topic:  eventbus.HOME_SHUTDOWN,
				Origin: "home",
			})
		}
	}()

	logrus.Infof("[Home] Geo-Location set to: Lat=%f Long=%f", core.Global.Latitude, core.Global.Longitude)

	service.ServiceRegistry.Register(&backend.Component{
		Name: "core",
	}, "shutdown_home", "Shutdown home", shutdownHome, map[string]string{}, map[string]string{})

	eventbus.EventBus.Start()

	backendConfig, _ := config.List("backends")
	backend.DefaultManager.StartBackendsByConfig(backendConfig)

	eventbus.EventBus.Subscribe(eventbus.HOME_SHUTDOWN, func(event eventbus.Event) {
		backend.DefaultManager.StopBackends()
	})

	core.PluginManager.Start(config)

	core.StateTracker.Start()
	service.ServiceRegistry.Start()

	eventbus.EventBus.Publish(eventbus.Event{
		Topic:  eventbus.HOME_STARTED,
		Origin: "home",
	})

	eventbus.EventBus.Wait()
}
Exemple #3
0
func main() {

	app := cli.NewApp()

	app.Name = "pipes_api"
	app.Author = "Francis Bouvier <*****@*****.**>"
	app.Version = "0.1.0"
	app.Usage = "API for pipes, micro-services framework"
	app.Flags = []cli.Flag{logLevelFlag}

	app.Action = func(c *cli.Context) {
		switch c.String("log") {
		case "debug":
			log.SetLevel(log.DebugLevel)
		case "warn":
			log.SetLevel(log.WarnLevel)
		default:
			log.SetLevel(log.InfoLevel)
		}

		storeAddr := c.Args()[0]
		projectID := c.Args()[1]
		addr := "0.0.0.0:8080"
		if err := launch(storeAddr, projectID, addr); err != nil {
			log.Fatalln(err)
		}
	}
	app.Run(os.Args)
}
Exemple #4
0
// InitLog initializes the logrus logger
func InitLog(logLevel, formatter string) error {

	switch formatter {
	case LogStashFormatter:
		logrus.SetFormatter(&logstash.LogstashFormatter{
			TimestampFormat: time.RFC3339,
		})
	default:
		logrus.SetFormatter(&logrus.TextFormatter{
			ForceColors:   true,
			FullTimestamp: true,
		})
	}

	logrus.SetOutput(os.Stdout)

	level, err := logrus.ParseLevel(logLevel)

	if err != nil {
		logrus.SetLevel(logrus.DebugLevel)
		return err
	}

	logrus.SetLevel(level)
	return nil
}
Exemple #5
0
func ParseArgs(config *Config) {
	configfile := flag.String("config", "etc/ssologin.json", "config file (JSON)")
	flag.BoolVar(&config.Debug, "debug", false, "Debug-level output")
	flag.Parse()

	// Read the config file
	c, err := ioutil.ReadFile(*configfile)
	CheckError(err)

	// Unmarshal the config file
	err = json.Unmarshal(c, &config)
	CheckError(err)

	// Convert Expiration (int) to time type
	config.Expiry = time.Duration(config.Expiration) * time.Second

	// Set appropriate log-level
	if config.Debug {
		log.SetLevel(log.DebugLevel)
	} else {
		log.SetLevel(log.InfoLevel)
	}

	privkey, err := ssocookie.ReadECCPrivateKeyPem(config.Privkeyfile)
	CheckError(err)
	config.Privkey = privkey
}
Exemple #6
0
func main() {
	app := cli.NewApp()
	app.Name = path.Base(os.Args[0])
	app.Usage = "An entropy and failure injection management API for Docker platforms."
	app.Version = VERSION
	app.Authors = []cli.Author{{Name: "Jeff Nickoloff", Email: "*****@*****.**"}}
	app.Flags = flags
	app.Commands = commands
	app.Before = func(c *cli.Context) error {
		log.SetOutput(os.Stderr)
		level, err := log.ParseLevel(c.String("log-level"))
		if err != nil {
			log.Fatalf(err.Error())
		}
		log.SetLevel(level)

		// If a log level wasn't specified and we are running in debug mode,
		// enforce log-level=debug.
		if !c.IsSet("log-level") && !c.IsSet("l") && c.Bool("debug") {
			log.SetLevel(log.DebugLevel)
		}

		return nil
	}

	if err := app.Run(os.Args); err != nil {
		log.Fatal(err)
	}
}
func main() {

	flag.Parse()
	cpus := runtime.NumCPU()
	runtime.GOMAXPROCS(cpus)

	log.SetFormatter(&log.JSONFormatter{})
	log.SetOutput(os.Stderr)
	if *env == "production" {
		log.SetLevel(log.WarnLevel)
	} else {
		log.SetLevel(log.DebugLevel)
	}
	log.Infoln("Starting server...")

	// load config
	d, err := ioutil.ReadFile(*configFile)
	if err != nil {
		log.Fatalln("[ERROR] read config.yml", err)
	}

	cfg, err := config.Load(bytes.NewReader(d), *env)
	if err != nil {
		log.Fatalln("[ERROR] config Load", err)
	}
	psAll := sphinx.NewSphinx(cfg.PSConfig, cpus)

	ctx := context.Background()
	ctx = sphinx.NewContext(ctx, psAll)
	kami.Context = ctx
	kami.Serve()
}
Exemple #8
0
func main() {

	need_help := flag.Bool("h", false, "Show help")
	is_server := flag.Bool("s", false, "Run as server")
	verbose := flag.Bool("v", false, "More verbose output")
	cpuprofile := flag.String("cpuprofile", "", "Write cpu profile to file")
	flag.Parse()

	log.SetFormatter(&LogFormatter{&log.TextFormatter{
		FullTimestamp:   true,
		TimestampFormat: time.RFC822,
	}, "JUSTVPN"})
	log.SetLevel(log.InfoLevel)
	if *verbose {
		log.SetLevel(log.DebugLevel)
	}
	if *need_help {
		fmt.Printf("Usage: %v [OPTIONS] config.json\n", os.Args[0])
		flag.PrintDefaults()
		os.Exit(0)
	}
	if *is_server {
		log.Info("Running as server!")
	}
	if *cpuprofile != "" {
		log.Info("Saving CPU profile to %v", *cpuprofile)
		if f, err := os.Create(*cpuprofile); err != nil {
			log.Fatal(err)
		} else {
			pprof.StartCPUProfile(f)
			defer pprof.StopCPUProfile()
		}
	}

	if flag.NArg() == 0 {
		log.Fatal("Config file missing")
	}

	json_content, err := ioutil.ReadFile(flag.Arg(0))
	if err != nil {
		log.WithField("filename", flag.Arg(0)).Fatal("Error reading config file")
	}

	vpn := justvpn.VPN{}
	defer vpn.Destroy()
	if err = vpn.Init(*is_server, json_content); err != nil {
		log.WithField("error", err).Error("Error initing VPN")
		return
	}

	vpn.Start()

	signal_chan := make(chan os.Signal, 1)
	signal.Notify(signal_chan, os.Interrupt)

	select {
	case <-signal_chan:
		fmt.Println("CTRL-C Pressed")
	}
}
Exemple #9
0
func InitializeLogger(developerModeFlag bool) {
	logger = log.New()

	if developerModeFlag {
		customFormatter := new(log.TextFormatter)
		customFormatter.FullTimestamp = true
		customFormatter.TimestampFormat = "2006-01-02 15:04:05"
		log.SetFormatter(customFormatter)

		log.SetLevel(log.DebugLevel)
		logger.Level = log.DebugLevel
		logger.Formatter = customFormatter
	} else {
		customFormatter := new(log.JSONFormatter)
		customFormatter.TimestampFormat = "2006-01-02 15:04:05"

		log.SetFormatter(customFormatter)
		customFormatter.DisableTimestamp = false

		log.SetLevel(log.InfoLevel)
		logger.Level = log.InfoLevel
		logger.Formatter = customFormatter
	}

	logger.Out = os.Stdout

}
Exemple #10
0
func NewCustomizedLogger(level string, developerModeFlag bool) (*log.Logger, error) {
	logger := log.New()

	lv, err := log.ParseLevel(level)
	if err != nil {
		return nil, err
	}
	logger.Level = lv

	if developerModeFlag {
		customFormatter := new(log.TextFormatter)
		customFormatter.FullTimestamp = true
		customFormatter.TimestampFormat = "2006-01-02 15:04:05"
		log.SetFormatter(customFormatter)

		log.SetLevel(log.DebugLevel)
		logger.Level = lv
		logger.Formatter = customFormatter
	} else {
		customFormatter := new(log.JSONFormatter)
		customFormatter.TimestampFormat = "2006-01-02 15:04:05"

		log.SetFormatter(customFormatter)
		customFormatter.DisableTimestamp = false

		log.SetLevel(log.InfoLevel)
		logger.Level = lv
		logger.Formatter = customFormatter
	}

	logger.Out = os.Stdout

	return logger, nil
}
func TestRunWithTimeoutFailed(t *testing.T) {

	log.SetLevel(log.DebugLevel)
	defer log.SetLevel(log.InfoLevel)

	tmp, _ := ioutil.TempFile("", "tmp")
	defer os.Remove(tmp.Name())

	log.SetOutput(tmp)
	defer log.SetOutput(os.Stdout)

	cmd, _ := NewCommand("./testdata/test.sh failStuff --debug", "100ms")
	fields := log.Fields{"process": "test"}
	if err := RunWithTimeout(cmd, fields); err == nil {
		t.Errorf("Expected error but got nil")
	}
	time.Sleep(200 * time.Millisecond)

	buf, _ := ioutil.ReadFile(tmp.Name())
	logs := string(buf)

	if strings.Contains(logs, "timeout after") {
		t.Fatalf("RunWithTimeout failed to cancel timeout after failure: %v", logs)
	}
}
func SetLoggingLevel(debug bool) {
	if debug {
		log.SetLevel(log.DebugLevel)
	} else {
		log.SetLevel(log.InfoLevel)
	}
}
Exemple #13
0
func setDebugMode(debug bool) {
	if !debug {
		logrus.SetLevel(logrus.InfoLevel)
	} else {
		logrus.SetLevel(logrus.DebugLevel)
	}
}
Exemple #14
0
func main() {

	// configure logging
	logrus.SetLevel(logrus.InfoLevel)
	logrus.SetFormatter(&logrus.TextFormatter{FullTimestamp: true})

	// options to change log level
	globalOptions.Quiet = func() {
		logrus.SetLevel(logrus.WarnLevel)
	}
	globalOptions.Verbose = func() {
		logrus.SetLevel(logrus.DebugLevel)
	}
	globalOptions.LogJSON = func() {
		logrus.SetFormatter(&logrus.JSONFormatter{})
	}
	globalOptions.LogSyslog = func() {
		setupSyslog()
	}

	originalArgs = os.Args
	if _, err := parser.Parse(); err != nil {
		os.Exit(1)
	}
}
Exemple #15
0
// initConfig reads in config file and ENV variables if set.
func initConfig() {
	if len(cfgFile) != 0 {
		viper.SetConfigFile(cfgFile)
	}

	viper.SetConfigName(".otp-config")
	viper.AddConfigPath("$HOME")
	viper.AutomaticEnv()

	apiKey, _ := RootCmd.Flags().GetString("api-key")
	if len(apiKey) == 0 && len(os.Getenv("GITHUB_API_KEY")) > 0 {
		RootCmd.Flags().Set("api-key", os.Getenv("GITHUB_API_KEY"))
	}
	if len(apiKey) > 0 {
		if err := os.Setenv("GITHUB_API_KEY", apiKey); err != nil {
			fmt.Fprintf(os.Stderr, "Error: Unable to set GITHUB_API_KEY\n")
			os.Exit(1)
		}
	}

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

	log.SetFormatter(&log.TextFormatter{})
	log.SetOutput(os.Stderr)
	if api.Verbose {
		log.SetLevel(log.DebugLevel)
	} else {
		log.SetLevel(log.WarnLevel)
	}
}
Exemple #16
0
func (t *tether) setLogLevel() {
	// TODO: move all of this into an extension.Pre() block when we move to that model
	// adjust the logging level appropriately
	switch t.config.DebugLevel {
	case 0:
		log.SetLevel(log.InfoLevel)
		// TODO: do not echo application output to console without debug enabled
		serial.DisableTracing()
	case 1:
		log.SetLevel(log.DebugLevel)
		serial.DisableTracing()
	case 2:
		log.SetLevel(log.DebugLevel)
		serial.EnableTracing()

		log.Info("Launching pprof server on port 6060")
		fn := func() {
			go http.ListenAndServe("0.0.0.0:6060", nil)
		}

		once.Do(fn)
	default:
		log.SetLevel(log.DebugLevel)
		logConfig(t.config)
	}
}
Exemple #17
0
func main() {
	envflag.Parse()

	if *debug {
		logrus.SetLevel(logrus.DebugLevel)
	} else {
		logrus.SetLevel(logrus.WarnLevel)
	}

	handler := router.Load(
		ginrus.Ginrus(logrus.StandardLogger(), time.RFC3339, true),
		middleware.Version,
		middleware.Store(),
		middleware.Remote(),
		middleware.Cache(),
	)

	if *cert != "" {
		logrus.Fatal(
			http.ListenAndServeTLS(*addr, *cert, *key, handler),
		)
	} else {
		logrus.Fatal(
			http.ListenAndServe(*addr, handler),
		)
	}
}
Exemple #18
0
func LoadSettingsFromFile() {
	viper.SetConfigType(ConfigType)
	setConfigLocation()

	// Set defaults
	viper.SetDefault("Port", Port)
	viper.SetDefault("EnableAutomerge", EnableAutomerge)
	viper.SetDefault("Debug", Debug)
	viper.SetDefault("DefaultEnvironment", DefaultEnvironment)
	viper.SetDefault("DefaultTask", DefaultTask)
	viper.SetDefault("BoltdbName", BoltdbName)

	// Load configuration
	err := viper.ReadInConfig()
	if err != nil {
		log.Warning("Configuration not found, loading defaults")
	}

	// set log level
	if viper.GetBool("Debug") {
		log.SetLevel(log.DebugLevel)
	} else {
		log.SetLevel(log.InfoLevel)
	}

	log.Debugf("Loaded setting values: %v", viper.AllSettings())
	log.Info("Settings loaded")
}
Exemple #19
0
func init() {
	cmf, err := os.Open("casemanager.conf")
	if err != nil {
		logrus.Fatal(err)
		return
	}
	defer cmf.Close()

	if err = json.NewDecoder(cmf).Decode(&pubConfig); err != nil {
		logrus.Fatal(err)
		return
	}

	if pubConfig.Debug {
		logrus.SetLevel(logrus.DebugLevel)
	} else {
		logrus.SetLevel(logrus.WarnLevel)
	}

	db := liboct.GetDefaultDB()
	db.RegistCollect(liboct.DBCase)
	db.RegistCollect(liboct.DBRepo)
	db.RegistCollect(liboct.DBTask)

	repos := pubConfig.Repos
	for index := 0; index < len(repos); index++ {
		if err := repos[index].IsValid(); err != nil {
			logrus.Warnf("The repo ", repos[index], " is invalid. ", err.Error())
			continue
		}
		if id, err := db.Add(liboct.DBRepo, repos[index]); err == nil {
			RefreshRepo(id)
		}
	}
}
Exemple #20
0
func init() {
	of, err := os.Open("octd.conf")
	if err != nil {
		logrus.Fatal(err)
		return
	}
	defer of.Close()

	if err = json.NewDecoder(of).Decode(&pubConfig); err != nil {
		logrus.Fatal(err)
		return
	}

	if pubConfig.Class == "container" {
		cmd := exec.Command("/bin/sh", "-c", pubConfig.ContainerDaemon)
		cmd.Stdin = os.Stdin
		if _, err := cmd.CombinedOutput(); err != nil {
			logrus.Fatal(err)
			return
		}
	}

	if pubConfig.Debug {
		logrus.SetLevel(logrus.DebugLevel)
	} else {
		logrus.SetLevel(logrus.InfoLevel)
	}

	db := liboct.GetDefaultDB()
	db.RegistCollect(liboct.DBTask)

	RegisterToTestServer()
}
Exemple #21
0
func main() {
	// let the user enter the number of points to be used
	numPoints := flag.Int("points", 1000, "Number of points to be generated")
	filename := flag.String("output", "curve", "name of the file where the image will be written")
	size := flag.Int("size", 1024, "Size of the file to be generated")
	debug := flag.Bool("d", false, "Print debug information")
	flag.Parse()

	if *debug {
		log.SetLevel(log.DebugLevel)
		log.Debug("Debug enabled")
	} else {
		log.SetLevel(log.InfoLevel)
	}

	runtime.GOMAXPROCS(runtime.NumCPU())
	file := fmt.Sprintf("%s.png", *filename)
	log.Info("Starting program")
	pl := point.RandomSlice(*numPoints)
	log.Info("Calculating matrix")
	m := matrix.FindSmallerCellSize(&pl)
	//fmt.Println("Initial matrix: ", m)
	canvas := drawing.NewCanvas(*size, file)
	strat := strategy.NewSnake(len(m.Squares))
	m.Draw(canvas, *strat)
	log.Info("Saving the image (this process might take a few minutes)")
	canvas.Save()
	log.Info("Finished program")
}
Exemple #22
0
// Returns a singleton instance of API, intialised with an empty DB containing a
// single user
func getTestApi() *Grapi {
	if test_api != nil {
		return test_api
	}

	// Set Log level here. This should only be called once, and near the start
	// of the test run
	logLevel := 0
	if !*verboseAPI {
		log.SetLevel(log.PanicLevel)
	} else {
		logLevel = 1
		log.SetLevel(log.DebugLevel)
	}

	db := getTestDb()
	a := New(Options{JwtKey: "RandomString", Db: db, LogLevel: logLevel})

	a.AddDefaultRoutes(&PrivateWidget{}, RouteOptions{UseDefaultAuth: true})
	a.AddDefaultRoutes(&Widget{})
	a.AddDefaultRoutes(&VerifiedWidget{})
	a.AddDefaultRoutes(&Widget{}, RouteOptions{UriModelName: "other_widgets"})

	a.AddDefaultRoutes(&User{})
	a.SetAuth(&User{}, "auth")

	test_api = a
	return a
}
Exemple #23
0
func Action(c *cli.Context) {
	if len(c.Args()) != 1 {
		logrus.Fatalf("usage: gotty-client [GoTTY URL]")
	}

	// setting up logrus
	logrus.SetOutput(os.Stderr)
	if c.Bool("debug") {
		logrus.SetLevel(logrus.DebugLevel)
	} else {
		logrus.SetLevel(logrus.InfoLevel)
	}

	// create Client
	url := c.Args()[0]
	client, err := gottyclient.NewClient(url)
	if err != nil {
		logrus.Fatalf("Cannot create client: %v", err)
	}

	if c.Bool("skip-tls-verify") {
		client.SkipTLSVerify = true
	}

	// loop
	if err = client.Loop(); err != nil {
		logrus.Fatalf("Communication error: %v", err)
	}
}
Exemple #24
0
func main() {

	flag.Parse()

	if flLogLevel != "" {
		lvl, err := logrus.ParseLevel(flLogLevel)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Unable to parse logging level: %s\n", flLogLevel)
			os.Exit(1)
		}
		logrus.SetLevel(lvl)
	} else {
		logrus.SetLevel(logrus.InfoLevel)
	}

	if flDebug {
		logrus.SetLevel(logrus.DebugLevel)
	}

	d, err := rbd.NewRbdDriver(root, graphOptions)
	if err != nil {
		logrus.Errorf("Create rbd driver failed: %v", err)
		os.Exit(1)
	}
	h := degraph.NewHandler(d)
	logrus.Infof("listening on %s\n", socketAddress)
	fmt.Println(h.ServeUnix("root", socketAddress))
}
Exemple #25
0
func init() {
	log.SetOutput(os.Stderr)
	log.SetLevel(log.InfoLevel)
	if os.Getenv("DEBUG") != "" {
		log.SetLevel(log.DebugLevel)
	}
}
Exemple #26
0
func (f *filePublisher) Publish(metrics []plugin.Metric, config plugin.Config) error {
	log.SetFormatter(&log.TextFormatter{DisableTimestamp: true})
	if _, err := config.GetBool(debug); err == nil {
		log.SetLevel(log.DebugLevel)
	} else {
		log.SetLevel(log.InfoLevel)
	}
	log.Debug("publishing started")

	filename, err := config.GetString("file")
	if err != nil {
		log.Error(err)
		return err
	}

	file, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0666)
	defer file.Close()
	if err != nil {
		log.Error(err)
		return err
	}
	log.WithFields(log.Fields{
		"file": filename,
		"metrics-published-count": len(metrics),
	}).Debug("metrics published")
	w := bufio.NewWriter(file)
	for _, m := range metrics {
		formattedTags := formatMetricTagsAsString(m.Tags)
		w.WriteString(fmt.Sprintf("%v|%v|%v|%v\n", m.Timestamp, m.Namespace, m.Data, formattedTags))
	}
	w.Flush()

	return nil
}
func setupLogger(cmd *cobra.Command, args []string) {
	if verbose, _ := cmd.Flags().GetBool(VerboseFlag); verbose {
		log.SetLevel(log.DebugLevel)
	} else {
		log.SetLevel(log.InfoLevel)
	}
}
Exemple #28
0
func initLogrus(ctx *cli.Context) {
	logrus.SetFormatter(&logrus.TextFormatter{
		TimestampFormat: time.RFC822,
		FullTimestamp:   true,
	})

	if level, err := logrus.ParseLevel(ctx.String("log_level")); err == nil {
		logrus.SetLevel(level)
	} else {
		log.Error(err)
		logrus.SetLevel(logrus.InfoLevel)
	}

	filename := ctx.String("log_file")
	logrus.SetOutput(os.Stderr)
	if filename != "" {
		var f *os.File
		_, err := os.Stat(filename)
		if !os.IsNotExist(err) {
			os.Rename(filename, filename+".prev")
		}
		f, err = os.Create(filename)
		if err != nil {
			log.Error("Cannot create log file ", err)
			log.Warning("Continuing to log to stderr")
		} else {
			logrus.SetOutput(f)
		}
	}
}
Exemple #29
0
func main() {
	// Set log options.
	log.SetOutput(os.Stderr)
	log.SetLevel(log.WarnLevel)

	// Options.
	var opts struct {
		Verbose     bool   `short:"v" long:"verbose" description:"Verbose"`
		Version     bool   `long:"version" description:"Version"`
		BindAddr    string `short:"b" long:"bind-addr" description:"Bind to address" default:"0.0.0.0"`
		Port        int    `short:"p" long:"port" description:"Port" default:"5050"`
		StaticDir   string `short:"s" long:"static-dir" description:"Static content" default:"static"`
		TemplateDir string `short:"t" long:"template-dir" description:"Templates" default:"templates"`
	}

	// Parse options.
	if _, err := flags.Parse(&opts); err != nil {
		ferr := err.(*flags.Error)
		if ferr.Type == flags.ErrHelp {
			os.Exit(0)
		} else {
			log.Fatal(err.Error())
		}
	}

	// Print version.
	if opts.Version {
		fmt.Printf("peekaboo %s\n", Version)
		os.Exit(0)
	}

	// Set verbose.
	if opts.Verbose {
		log.SetLevel(log.InfoLevel)
	}

	// Check root.
	if runtime.GOOS != "darwin" && os.Getuid() != 0 {
		log.Fatal("This application requires root privileges to run.")
	}

	info, err := hwinfo.Get()
	if err != nil {
		log.Fatal(err.Error())
	}

	log.Infof("Using static dir: %s", opts.StaticDir)
	log.Infof("Using template dir: %s", opts.TemplateDir)

	m := macaron.Classic()
	m.Use(macaron.Static(opts.StaticDir))
	m.Use(macaron.Renderer(macaron.RenderOptions{
		Directory:  opts.TemplateDir,
		IndentJSON: true,
	}))

	routes(m, info)
	m.Run(opts.BindAddr, opts.Port)
}
Exemple #30
0
// Entry point of oci2aci,
// First convert oci layout to aci layout, then build aci layout to image.
func RunOCI2ACI(args []string, flagDebug bool, flagName string) error {
	var srcPath, dstPath string

	srcPath = args[0]
	if len(args) == 1 {
		dstPath = ""
	} else {
		dstPath = args[1]
		ext := filepath.Ext(dstPath)
		if ext != schema.ACIExtension {
			errStr := fmt.Sprintf("Extension must be %s (given %s)", schema.ACIExtension, ext)
			err := errors.New(errStr)
			return err
		}
	}

	if flagDebug {
		logrus.SetLevel(logrus.DebugLevel)
	} else {
		logrus.SetLevel(logrus.InfoLevel)
	}

	manifestName = flagName
	_, err := types.NewACName(manifestName)
	if err != nil {
		return err
	}

	if bValidate := validateOCIProc(srcPath); bValidate != true {
		logrus.Infof("Conversion stop.")
		return nil
	}

	dirWork := createWorkDir()
	// First, convert layout
	manifestPath, err := convertLayout(srcPath, dirWork)
	if err != nil {
		logrus.Debugf("Conversion from oci to aci layout failed: %v", err)
	} else {
		logrus.Debugf("Manifest:%v generated successfully.", manifestPath)
	}
	// Second, build image
	imgPath, err := buildACI(dirWork)
	if err != nil {
		logrus.Debugf("Generate aci image failed:%v", err)
	} else {
		logrus.Debugf("Image:%v generated successfully.", imgPath)
	}
	// Save aci image to the path user specified
	if dstPath != "" {
		if err = run(exec.Command("cp", imgPath, dstPath)); err != nil {
			logrus.Debugf("Store aci image failed:%v", err)
		} else {
			logrus.Debugf("Image:%v generated successfully", dstPath)
		}
	}

	return nil
}