Esempio n. 1
0
func main() {
	pflag.Parse()

	viper.SetConfigName("config")
	viper.AddConfigPath(".")

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

	if err := viper.ReadInConfig(); err != nil {
		logrus.Fatal(err)
	}

	nick := viper.GetString("twitch.nick")
	pass := viper.GetString("twitch.pass")
	channels := viper.GetStringSlice("twitch.join")
	dbFilename := viper.GetString("database.filename")
	superusers := viper.GetStringSlice("permissions.superusers")

	bot := bot.NewBot(nick, pass, channels, dbFilename, superusers)
	if err := bot.Start(); err != nil {
		logrus.Fatal(err)
	}

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	<-c
	fmt.Print("\r\r\b")

	if err := bot.Stop(); err != nil {
		logrus.Fatal(err)
	}
}
Esempio n. 2
0
func main() {
	startTime := currentTimeMillis()

	transportFactory := thrift.NewTFramedTransportFactory(thrift.NewTTransportFactory())
	protocolFactory := thrift.NewTBinaryProtocolFactoryDefault()

	transport, err := thrift.NewTSocket(NETWORK_ADDR)
	if err != nil {
		logrus.Fatal(os.Stderr, "error resolving address:", err)
	}

	useTransport := transportFactory.GetTransport(transport)
	client := rpc.NewSessionManagerClientFactory(useTransport, protocolFactory)
	if err := transport.Open(); err != nil {
		logrus.Fatal(os.Stderr, "Error opening socket to "+NETWORK_ADDR, err)
	}
	defer transport.Close()

	// 开始调用服务的接口
	ctx := rpc.NewSessionContext()

	sid, _ := client.CreateSession(ctx)
	logrus.Infof("创新新的会话id => %s", sid)

	ctx, _ = client.GetSession(sid)
	logrus.Infof("获取会话上下文 => %+v", ctx)

	endTime := currentTimeMillis()
	logrus.Infof("本次调用用时: %d 毫秒", endTime-startTime)

}
Esempio n. 3
0
func join(c *cli.Context) {
	dflag := getDiscovery(c)
	if dflag == "" {
		log.Fatalf("discovery required to join a cluster. See '%s join --help'.", c.App.Name)
	}

	addr := c.String("advertise")
	if addr == "" {
		log.Fatal("missing mandatory --advertise flag")
	}
	if !checkAddrFormat(addr) {
		log.Fatal("--advertise should be of the form ip:port or hostname:port")
	}

	joinDelay, err := time.ParseDuration(c.String("delay"))
	if err != nil {
		log.Fatalf("invalid --delay: %v", err)
	}
	if joinDelay < time.Duration(0)*time.Second {
		log.Fatalf("--delay should not be a negative number")
	}

	hb, err := time.ParseDuration(c.String("heartbeat"))
	if err != nil {
		log.Fatalf("invalid --heartbeat: %v", err)
	}
	if hb < 1*time.Second {
		log.Fatal("--heartbeat should be at least one second")
	}
	ttl, err := time.ParseDuration(c.String("ttl"))
	if err != nil {
		log.Fatalf("invalid --ttl: %v", err)
	}
	if ttl <= hb {
		log.Fatal("--ttl must be strictly superior to the heartbeat value")
	}

	d, err := discovery.New(dflag, hb, ttl, getDiscoveryOpt(c))
	if err != nil {
		log.Fatal(err)
	}

	// if joinDelay is 0, no delay will be executed
	// if joinDelay is larger than 0,
	// add a random delay between 0s and joinDelay at start to avoid synchronized registration
	if joinDelay > 0 {
		r := rand.New(rand.NewSource(time.Now().UTC().UnixNano()))
		delay := time.Duration(r.Int63n(int64(joinDelay)))
		log.Infof("Add a random delay %s to avoid synchronized registration", delay)
		time.Sleep(delay)
	}

	for {
		log.WithFields(log.Fields{"addr": addr, "discovery": dflag}).Infof("Registering on the discovery service every %s...", hb)
		if err := d.Register(addr); err != nil {
			log.Error(err)
		}
		time.Sleep(hb)
	}
}
Esempio n. 4
0
func before(c *cli.Context) error {
	initLogFormatter()
	initHelpAndVersionFlags()
	initAppHelpTemplate()

	// Log level
	if logLevel, err := log.ParseLevel(c.String(LogLevelKey)); err != nil {
		log.Fatal("[BITRISE_CLI] - Failed to parse log level:", err)
	} else {
		log.SetLevel(logLevel)
	}

	// Befor parsing cli, and running command
	// we need to decide wich path will be used by envman
	envman.CurrentEnvStoreFilePath = c.String(PathKey)
	if envman.CurrentEnvStoreFilePath == "" {
		if path, err := envStorePathInCurrentDir(); err != nil {
			log.Fatal("[ENVMAN] - Failed to set envman work path in current dir:", err)
		} else {
			envman.CurrentEnvStoreFilePath = path
		}
	}

	envman.ToolMode = c.Bool(ToolKey)
	if envman.ToolMode {
		log.Info("[ENVMAN] - Tool mode on")
	}

	if _, err := envman.GetConfigs(); err != nil {
		log.Fatal("[ENVMAN] - Failed to init configs:", err)
	}

	return nil
}
Esempio n. 5
0
func decompress() {
	log.Info("Decompressing Riak Explorer")

	var err error
	if err := os.Mkdir("riak_explorer", 0777); err != nil {
		log.Fatal("Unable to make rex directory: ", err)
	}

	asset, err := artifacts.Asset("trusty.tar.gz")
	if err != nil {
		log.Fatal(err)
	}
	if err = common.ExtractGZ("riak_explorer", bytes.NewReader(asset)); err != nil {
		log.Fatal("Unable to extract trusty root: ", err)
	}
	asset, err = artifacts.Asset("riak_explorer-bin.tar.gz")

	if err != nil {
		log.Fatal(err)
	}
	if err = common.ExtractGZ("riak_explorer", bytes.NewReader(asset)); err != nil {
		log.Fatal("Unable to extract rex: ", err)
	}

}
Esempio n. 6
0
func main() {
	err := jq.Init()
	if err != nil {
		log.Fatal(err)
	}

	log.WithFields(log.Fields{
		"version": jq.Version,
		"path":    jq.Path,
	}).Info("initialized jq")

	conf, err := config.Load()
	if err != nil {
		log.Fatal(err)
	}

	log.WithFields(log.Fields{
		"host": conf.Host,
		"port": conf.Port,
	}).Infof("Starting server at %s:%s", conf.Host, conf.Port)
	srv := server.New(conf)
	err = srv.Start()
	if err != nil {
		log.WithError(err).Fatal("error starting sever")
	}
}
Esempio n. 7
0
func add(c *cli.Context) {
	log.Debugln("[ENVMAN] - Work path:", envman.CurrentEnvStoreFilePath)

	key := c.String(KeyKey)
	expand := !c.Bool(NoExpandKey)
	replace := !c.Bool(AppendKey)

	var value string
	if stdinValue != "" {
		value = stdinValue
	} else if c.IsSet(ValueKey) {
		value = c.String(ValueKey)
	} else if c.String(ValueFileKey) != "" {
		if v, err := loadValueFromFile(c.String(ValueFileKey)); err != nil {
			log.Fatal("[ENVMAN] - Failed to read file value: ", err)
		} else {
			value = v
		}
	}

	if err := addEnv(key, value, expand, replace); err != nil {
		log.Fatal("[ENVMAN] - Failed to add env:", err)
	}

	log.Debugln("[ENVMAN] - Env added")

	if err := logEnvs(); err != nil {
		log.Fatal("[ENVMAN] - Failed to print:", err)
	}
}
Esempio n. 8
0
func logoutRegistry(ctx *cobra.Command, args []string) {
	reg := client.INDEX_SERVER
	if len(args) > 0 {
		reg = args[0]
	}

	config, err := client.LoadConfig(configPath)
	if err != nil {
		log.Fatal(err)
	}

	registry, notFound := config.GetRegistry(reg)
	if (notFound != nil) || (registry.Credentials == "") {
		log.Fatalf("Not logged in to a Docker registry at %s", reg)
	}

	config.LogoutRegistry(reg)

	if err := config.SaveConfig(configPath); err != nil {
		log.Fatal(err)
	}

	ctx.Printf("Removed login credentials for a Docker registry at %s\n\n", reg)

	listRegistries(ctx, args)
}
Esempio n. 9
0
func main() {
	log.Info("Starting rancher-metadata")
	parseFlags()
	err := loadAnswers()
	if err != nil {
		log.Fatal("Cannot startup without a valid Answers file")
	}
	watchSignals()

	router.HandleFunc("/favicon.ico", http.NotFound)
	router.HandleFunc("/", root).
		Methods("GET", "HEAD").
		Name("Root")

	for _, version := range versions {
		router.HandleFunc("/{version:"+version+"}", metadata).
			Methods("GET", "HEAD").
			Name("Version:" + version)

		router.HandleFunc("/{version:"+version+"}/{key:.*}", metadata).
			Methods("GET", "HEAD").
			Name("Metadata")
	}

	log.Info("Listening on ", *listen)
	log.Fatal(http.ListenAndServe(*listen, router))
}
Esempio n. 10
0
func procesImage(path string, f os.FileInfo, err error) error {
	if f.IsDir() {
		return nil
	}

	log.Debugf("Processing %s", path)

	extension := filepath.Ext(f.Name())
	if !isSupportPhotoType(strings.ToLower(extension)) {
		log.Warnf("%s's file type %s is unsupported", path, extension)
		return nil
	}

	reader := exif.New()

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

	str := fmt.Sprintf("%s", reader.Tags["Date and Time"])
	t := f.ModTime()

	if len(str) == 0 {
		log.Warnf("Date and Time EXIF tag missing for %s", path)
	} else {
		layout := "2006:01:02 15:04:05"
		t, err = time.Parse(layout, str)
		if err != nil {
			log.Fatal(err)
		}
	}

	newDir := fmt.Sprintf("%s/%4d/%02d/%02d", destPath, t.Year(), t.Month(), t.Day())

	err = os.MkdirAll(newDir, 0777)
	if err != nil {
		log.Fatal(err)
	}

	newFile := fmt.Sprintf("%s/%s", newDir, f.Name())

	if mode == "move" {
		log.Debugf("Moving %s %s", path, newFile)
		err = os.Rename(path, newFile)
	} else {
		if _, err := os.Stat(newFile); err == nil {
			log.Warnf("Photo %s already exists", newFile)
		} else {
			log.Debugf("Copying %s %s", path, newFile)
			err = copyFile(path, newFile)
		}
	}

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

	return nil
}
Esempio n. 11
0
func switchHost(ctx *cobra.Command, args []string) {
	if len(args) < 1 {
		ErrorExit(ctx, "Needs an argument <NAME> to switch")
	}

	name := args[0]

	config, err := client.LoadConfig(configPath)
	if err != nil {
		log.Fatal(err)
	}

	host, err := config.GetHost(name)
	if err != nil {
		log.Fatal(err)
	}

	config.Default = host.Name

	if err := config.SaveConfig(configPath); err != nil {
		log.Fatal(err)
	}

	listHosts(ctx, args)
}
Esempio n. 12
0
func (m *Mesos) loadFromMaster(ip string, port string) (sj state.State) {
	url := "http://" + ip + ":" + port + "/master/state.json"

	req, err := http.NewRequest("GET", url, nil)
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}

	err = json.Unmarshal(body, &sj)
	if err != nil {
		log.Fatal(err)
	}

	return sj
}
func (exp *exporter) main(c *cli.Context) {
	setupLogging(c)

	registry := newRegistry()

	collector, err := exp.Init(c, registry)
	if err != nil {
		log.Fatal(err)
	}

	if exp.Tick {
		collector.Collect(registry)
		interval := c.Int("interval")
		go func() {
			for _ = range time.Tick(time.Duration(interval) * time.Second) {
				if exp.ResetOnTick {
					registry.Reset()
				}
				collector.Collect(registry)
			}
		}()
	}

	http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		w.Header().Add("Location", exp.MetricsPath)
		w.WriteHeader(http.StatusFound)
	})
	http.Handle(exp.MetricsPath, prometheus.Handler())
	if err := http.ListenAndServe(fmt.Sprintf(":%d", c.Int("port")), nil); err != nil {
		log.Fatal(err)
	}
}
Esempio n. 14
0
// DeleteTestRun will remove an entire testrun entry from teh agent cache by UUID
func (ac AgentCache) DeleteTestRun(uuid string) error {

	// Open connection
	db, err := sql.Open("sqlite3", ac.db_loc)
	if err != nil {
		log.Error(err)
		return errors.New("Error accessing sqlite cache for DeleteTestRun")
	}
	defer db.Close()

	// Begin Update
	tx, err := db.Begin()
	if err != nil {
		log.Fatal(err)
		return errors.New("Error beginning new DeleteTestRun action")
	}

	stmt, err := tx.Prepare(fmt.Sprintf("delete from testruns where uuid = \"%s\" ", uuid))
	if err != nil {
		log.Fatal(err)
		return errors.New("Error preparing new DeleteTestRun action")
	}
	defer stmt.Close()
	_, err = stmt.Exec()
	if err != nil {
		log.Fatal(err)
		return errors.New("Error executing new DeleteTestRun action")
	}
	tx.Commit()

	return nil
}
Esempio n. 15
0
func main() {

	log.Info("starting NNTP server...")
	conf, err := config.Ensure("settings.json")
	if err != nil {
		log.Fatal(err)
	}

	if conf.Log == "debug" {
		log.SetLevel(log.DebugLevel)
	}

	serv := &nntp.Server{
		Config: conf.NNTP,
		Feeds:  conf.Feeds,
	}
	serv.Storage, err = store.NewFilesytemStorage(conf.Store.Path, false)
	if err != nil {
		log.Fatal(err)
	}
	l, err := net.Listen("tcp", conf.NNTP.Bind)
	if err != nil {
		log.Fatal(err)
	}
	log.Info("listening on ", l.Addr())
	err = serv.Serve(l)
	if err != nil {
		log.Fatal(err)
	}
}
Esempio n. 16
0
// Create a new RPC server
func NewRpcServer(portNo uint16) (*rpc.Server, net.Listener) {
	server := rpc.NewServer()

	// Listens on a port
	l, e := net.Listen("tcp", fmt.Sprintf(":%d", portNo))
	if e != nil {
		log.Fatal("listen error:", e)
	}

	log.Infof("RPC Server is listening on %s\n", l.Addr())

	// run in background
	go func() {
		for {
			conn, err := l.Accept()
			if err != nil {
				// if listener closed, just exit the groutine
				if strings.Contains(err.Error(), "use of closed network connection") {
					return
				}
				log.Fatal(err)
			}

			log.Infof("Server accepted connection to %s from %s\n", conn.LocalAddr(), conn.RemoteAddr())

			go server.ServeCodec(jsonrpc.NewServerCodec(conn))
		}
	}()

	return server, l
}
Esempio n. 17
0
File: main.go Progetto: subuk/vmango
func main() {
	flag.Parse()

	if *NAME == "" {
		log.Fatal("name required")
	}
	if *MEMORY == 0 {
		log.Fatal("memory required")
	}
	if *CPUS == 0 {
		log.Fatal("cpus required")
	}

	db, err := bolt.Open(*DB_PATH, 0600, nil)
	if err != nil {
		log.WithError(err).Fatal("failed to open database")
	}

	planrep := dal.NewBoltPlanrep(db)

	plan := &models.Plan{
		Name:     *NAME,
		Memory:   *MEMORY * 1024 * 1024,
		Cpus:     *CPUS,
		DiskSize: *DISK * 1024 * 1024 * 1024,
	}
	if err := planrep.Add(plan); err != nil {
		log.WithError(err).WithField("plan", plan).Fatal("failed to add ip address")
	}
}
func SetEnv() {
	flag.Parse()

	if *debug {
		log.SetLevel(log.DebugLevel)
	}

	if *logFile != "" {
		if output, err := os.OpenFile(*logFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666); err != nil {
			log.Fatalf("Failed to log to file %s: %v", *logFile, err)
		} else {
			log.SetOutput(output)
		}
	}

	textFormatter := &log.TextFormatter{
		FullTimestamp: true,
	}
	log.SetFormatter(textFormatter)

	if *catalogUrl == "" {
		err := "Halting Catalog service, Catalog github repo url not provided"
		log.Fatal(err)
		fmt.Errorf(err)
	}

	// Shutdown when parent dies
	if _, _, err := syscall.RawSyscall(syscall.SYS_PRCTL, syscall.PR_SET_PDEATHSIG, uintptr(syscall.SIGTERM), 0); err != 0 {
		log.Fatal("Failed to set parent death sinal, err")
	}
}
Esempio n. 19
0
File: main.go Progetto: nsf/sqlrace
func main() {
	flag.Parse()
	m := methodMap[*method]

	db, err := gorm.Open("mysql", "root:@tcp(127.0.0.1:3306)/test?charset=utf8&parseTime=True")
	if err != nil {
		logrus.Fatal("Database open error: ", err)
	}
	if err := db.DB().Ping(); err != nil {
		logrus.Fatal("Database ping error: ", err)
	}
	db.SingularTable(true)
	db.DropTable(&TestTable{})
	panicOnError(db.AutoMigrate(&TestTable{}).Error)

	c := int64(*iterNum * *goNum)
	panicOnError(db.Save(&TestTable{Counter: c}).Error)

	logrus.Infof("Initial counter state: %d", c)
	logrus.Infof("Number of decrements per goroutine: %d", *iterNum)
	logrus.Infof("Number of goroutines: %d", *goNum)
	logrus.Infof("Method: %s", *method)
	logrus.Infof("Method description:\n%s", strings.TrimSpace(methodDoc[*method]))
	done := make(chan bool)
	for i := 0; i < *goNum; i++ {
		go m(&db, *iterNum, done)
	}
	for i := 0; i < *goNum; i++ {
		<-done
	}

	var tt TestTable
	panicOnError(db.First(&tt, 1).Error)
	logrus.Infof("Result: %d", tt.Counter)
}
Esempio n. 20
0
func init() {
	err := envconfig.Process("HELEN", &Constants)
	if err != nil {
		logrus.Fatal(err)
	}

	if Constants.SteamDevAPIKey == "" {
		logrus.Warning("Steam api key not provided, setting SteamApiMockUp to true")
	}
	if Constants.PublicAddress == "" {
		Constants.PublicAddress = "http://" + Constants.ListenAddress
	}
	if Constants.MockupAuth {
		logrus.Warning("Mockup authentication enabled.")
	}

	_, err = url.Parse(Constants.PublicAddress)
	if err != nil {
		logrus.Fatal("Couldn't parse HELEN_PUBLIC_ADDR - ", err)
	}
	_, err = url.Parse(Constants.LoginRedirectPath)
	if err != nil {
		logrus.Fatal("Couldn't parse HELEN_SERVER_REDIRECT_PATH - ", err)
	}

	if Constants.GeoIP {
		logrus.Info("GeoIP support enabled")
	}
}
Esempio n. 21
0
File: config.go Progetto: Jdesk/os
func runImport(c *cli.Context) {
	var input io.ReadCloser
	var err error
	input = os.Stdin
	cfg, err := config.LoadConfig()

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

	inputFile := c.String("input")
	if inputFile != "" {
		input, err = os.Open(inputFile)
		if err != nil {
			log.Fatal(err)
		}
		defer input.Close()
	}

	bytes, err := ioutil.ReadAll(input)
	if err != nil {
		log.Fatal(err)
	}

	cfg, err = cfg.Import(bytes)
	if err != nil {
		log.Fatal(err)
	}

	if err := cfg.Save(); err != nil {
		log.Fatal(err)
	}
}
Esempio n. 22
0
//passwordPrompt prompts user to enter password twice and that the two entries are equivalent.
func passwordPrompt() string {
	fmt.Print("Enter password: "******"\nCould not read password:"******"\nConfirm password: "******"\nCould Not read password.")
		log.Fatal(errs)
		os.Exit(1)
	}

	if reflect.DeepEqual(password, passwordConfirm) == false {
		fmt.Println("\n")
		log.Fatal("Passwords do not match")
	}

	return strings.TrimSpace(string(password))
}
Esempio n. 23
0
func ConnectRPC(amqpConn *amqp.Connection) {
	if !*paulingDisabled {
		codec, err := amqprpc.NewClientCodec(amqpConn, config.Constants.PaulingQueue, amqprpc.JSONCodec{})
		if err != nil {
			logrus.Fatal(err)
		}

		pauling = rpc.NewClientWithCodec(codec)

	}
	if !*fumbleDisabled {
		codec, err := amqprpc.NewClientCodec(amqpConn, config.Constants.FumbleQueue, amqprpc.JSONCodec{})
		if err != nil {
			logrus.Fatal(err)
		}

		fumble = rpc.NewClientWithCodec(codec)
	}
	if !*twitchbotDisabled {
		codec, err := amqprpc.NewClientCodec(amqpConn, config.Constants.TwitchBotQueue, amqprpc.JSONCodec{})
		if err != nil {
			logrus.Fatal(err)
		}
		twitchbot = rpc.NewClientWithCodec(codec)
	}
}
Esempio n. 24
0
func (this *App) Run() {
	apiServer := rest.NewApi()
	apiServer.Use(rest.DefaultDevStack...)

	// Cors
	apiServer.Use(&rest.CorsMiddleware{
		RejectNonCorsRequests: false,
		OriginValidator: func(origin string, request *rest.Request) bool {
			return true
		},
		AllowedMethods: []string{"GET", "POST", "PUT"},
		AllowedHeaders: []string{
			"Authorization", "Accept", "Content-Type", "X-Custom-Header", "Origin",
		},
		AccessControlAllowCredentials: true,
		AccessControlMaxAge:           3600,
	})

	// Jsonp
	apiServer.Use(&rest.JsonpMiddleware{
		CallbackNameKey: "jsonp",
	})

	router, err := rest.MakeRouter(config.Routes...)
	if err != nil {
		log.Fatal(err)
	}

	apiServer.SetApp(router)

	log.Info("Start serving, port=", this.Env.Port)
	log.Fatal(http.ListenAndServe(this.Port(), apiServer.MakeHandler()))
}
Esempio n. 25
0
func main() {
	flag.Parse()

	log.SetOutput(os.Stdout)
	log.SetLevel(log.DebugLevel)

	var client *docker.Client
	if os.Getenv("DOCKER_HOST") != "" {
		var err error
		certPath := os.Getenv("DOCKER_CERT_PATH")
		client, err = docker.NewTLSClient(os.Getenv("DOCKER_HOST"), path.Join(certPath, "cert.pem"), path.Join(certPath, "key.pem"), path.Join(certPath, "ca.pem"))
		if err != nil {
			log.Fatal(err)
		}
	} else {
		var err error
		client, err = docker.NewClient("unix:///var/run/docker.sock")
		if err != nil {
			log.Fatal(err)
		}
	}

	handler := Handler{docker: client, domain: fmt.Sprintf("%s.", *domain)}

	server := dns.Server{}
	server.Handler = &handler
	server.Net = *network
	server.Addr = *addr

	err := server.ListenAndServe()
	if err != nil {
		log.Fatal(err)
	}
}
Esempio n. 26
0
func storagepoolAgent(c *cli.Context) {
	healthCheckInterval := c.GlobalInt("healthcheck-interval")
	healthCheckBaseDir := c.GlobalString("healthcheck-basedir")
	healthCheckType := c.String("storagepool-healthcheck-type")

	cattleUrl := c.GlobalString("url")
	cattleAccessKey := c.GlobalString("access-key")
	cattleSecretKey := c.GlobalString("secret-key")
	if c.GlobalBool("debug") {
		log.SetLevel(log.DebugLevel)
	}

	storagepoolRootDir := c.GlobalString("storagepool-rootdir")
	driver := c.GlobalString("storagepool-driver")
	if driver == "" {
		log.Fatal("required field storagepool-driver has not been set")
	}

	cattleClient, err := cattle.NewCattleClient(cattleUrl, cattleAccessKey, cattleSecretKey)
	if err != nil {
		log.Fatal(err)
	}

	storagepoolAgent := NewStoragepoolAgent(healthCheckInterval, storagepoolRootDir, driver, healthCheckBaseDir, healthCheckType, cattleClient)

	metadataUrl := c.String("storagepool-metadata-url")

	if err := storagepoolAgent.Run(metadataUrl); err != nil {
		log.Fatal(err)
	}
}
Esempio n. 27
0
File: service.go Progetto: rowhit/os
func enable(c *cli.Context) {
	changed := false
	cfg, err := config.LoadConfig()
	if err != nil {
		log.Fatal(err)
	}

	for _, service := range c.Args() {
		if val, ok := cfg.Rancher.ServicesInclude[service]; !ok || !val {
			if strings.HasPrefix(service, "/") && !strings.HasPrefix(service, "/var/lib/rancher/conf") {
				log.Fatalf("ERROR: Service should be in path /var/lib/rancher/conf")
			}
			if _, err := compose.LoadServiceResource(service, true, cfg); err != nil {
				log.Fatalf("could not load service %s", service)
			}
			cfg.Rancher.ServicesInclude[service] = true
			changed = true
		}
	}

	if changed {
		if err := cfg.Set("rancher.services_include", cfg.Rancher.ServicesInclude); err != nil {
			log.Fatal(err)
		}
	}
}
Esempio n. 28
0
// Read the snapd configuration from a configuration file
func readConfig(cfg *Config, fpath string) {
	var path string
	if !defaultConfigFile() && fpath == "" {
		return
	}
	if defaultConfigFile() && fpath == "" {
		path = defaultConfigPath
	}
	if fpath != "" {
		f, err := os.Stat(fpath)
		if err != nil {
			log.Fatal(err)
		}
		if f.IsDir() {
			log.Fatal("configuration path provided must be a file")
		}
		path = fpath
	}

	serrs := cfgfile.Read(path, &cfg, CONFIG_CONSTRAINTS)
	if serrs != nil {
		for _, serr := range serrs {
			log.WithFields(serr.Fields()).Error(serr.Error())
		}
		log.Fatal("Errors found while parsing global configuration file")
	}
}
Esempio n. 29
0
func main() {
	f, err := os.OpenFile("server0.log", os.O_APPEND|os.O_CREATE|os.O_RDWR, 0666)
	if err != nil {
		fmt.Printf("error opening file: %v", err)
	}

	// don't forget to close it
	defer f.Close()

	log.SetOutput(f)
	log.SetLevel(log.DebugLevel)

	globalData, err := platform.CreateGlobalData()
	if err != nil {
		log.Fatal(err)
		return
	}

	runtime.GOMAXPROCS(runtime.NumCPU())

	c, err := service.NewContester("server.ini", globalData)
	if err != nil {
		log.Fatal(err)
		return
	}

	rpc.Register(c)
	for {
		if err = rpc4go.ConnectServer(c.ServerAddress, rpc.DefaultServer); err != nil {
			log.Error(err)
			time.Sleep(time.Second * 5)
		}
	}
}
Esempio n. 30
0
func ProjectPort(p *project.Project, c *cli.Context) {
	if len(c.Args()) != 2 {
		logrus.Fatalf("Please pass arguments in the form: SERVICE PORT")
	}

	index := c.Int("index")
	protocol := c.String("protocol")

	service, err := p.CreateService(c.Args()[0])
	if err != nil {
		logrus.Fatal(err)
	}

	containers, err := service.Containers()
	if err != nil {
		logrus.Fatal(err)
	}

	if index < 1 || index > len(containers) {
		logrus.Fatalf("Invalid index %d", index)
	}

	output, err := containers[index-1].Port(fmt.Sprintf("%s/%s", c.Args()[1], protocol))
	if err != nil {
		logrus.Fatal(err)
	}
	fmt.Println(output)
}