コード例 #1
0
ファイル: riak_node.go プロジェクト: sargun/riak-mesos
func (riakNode *RiakNode) configureAdvanced(cepmdPort int) {

	data, err := Asset("data/advanced.config")
	if err != nil {
		log.Panic("Got error", err)
	}
	tmpl, err := template.New("advanced").Parse(string(data))

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

	// Populate template data from the MesosTask
	vars := advancedTemplateData{}
	vars.CEPMDPort = cepmdPort
	file, err := os.OpenFile("riak/riak/etc/advanced.config", os.O_TRUNC|os.O_CREATE|os.O_RDWR, 0664)

	defer file.Close()
	if err != nil {
		log.Panic("Unable to open file: ", err)
	}

	err = tmpl.Execute(file, vars)

	if err != nil {
		log.Panic("Got error", err)
	}
}
コード例 #2
0
ファイル: main.go プロジェクト: dz0ny/gobu
func run(version, cmd string, cmdArgs []string) *os.ProcessState {

	path := os.Getenv("PATH")
	cwd, err := os.Getwd()
	if err != nil {
		log.Panic(err)
	}
	goroot := filepath.Join(envPath, version, "go")

	os.Setenv("GO15VENDOREXPERIMENT", "1")
	os.Setenv("GOPATH", goPath)
	log.Println("GOPATH", goPath)
	os.Setenv("GOROOT", goroot)
	log.Println("GOROOT", goroot)

	// Sometimes we want to use tools from local install
	os.Setenv("PATH", goPath+"/bin:"+goroot+"/bin:"+path)

	pa := os.ProcAttr{
		Files: []*os.File{os.Stdin, os.Stdout, os.Stderr},
		Dir:   cwd,
	}

	proc, err := os.StartProcess(cmd, cmdArgs, &pa)
	if err != nil {
		log.Panic(err)
	}

	state, err := proc.Wait()
	if err != nil {
		log.Panic(err)
	}
	return state
}
コード例 #3
0
func (re *RiakExplorer) configureAdvanced(cepmdPort int) {
	data, err := Asset("advanced.config")
	if err != nil {
		log.Panic("Got error", err)
	}
	tmpl, err := template.New("advanced").Parse(string(data))

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

	// Populate template data from the MesosTask
	vars := advancedTemplateData{}
	vars.CEPMDPort = cepmdPort
	configpath := filepath.Join(".", "riak_explorer", "riak_explorer", "etc", "advanced.config")
	file, err := os.OpenFile(configpath, os.O_TRUNC|os.O_CREATE|os.O_RDWR, 0)

	defer file.Close()
	if err != nil {
		log.Panic("Unable to open file: ", err)
	}

	err = tmpl.Execute(file, vars)

	if err != nil {
		log.Panic("Got error", err)
	}
}
コード例 #4
0
ファイル: riak_node.go プロジェクト: glickbot/riak-mesos
func (riakNode *RiakNode) configureAdvanced(cepmdPort int) {

	fetchURI := fmt.Sprintf("%s/api/v1/clusters/%s/advancedConfig", riakNode.taskData.URI, riakNode.taskData.ClusterName)
	resp, err := http.Get(fetchURI)
	if err != nil {
		log.Error("Unable to fetch advanced config: ", err)
	}
	advancedConfig, err := ioutil.ReadAll(resp.Body)
	resp.Body.Close()
	if err != nil {
		log.Error("Unable to fetch advanced config: ", err)
	}

	tmpl, err := template.New("advanced").Parse(string(advancedConfig))

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

	// Populate template data from the MesosTask
	vars := advancedTemplateData{}
	vars.CEPMDPort = cepmdPort
	file, err := os.OpenFile("root/riak/etc/advanced.config", os.O_TRUNC|os.O_CREATE|os.O_RDWR, 0664)

	defer file.Close()
	if err != nil {
		log.Panic("Unable to open file: ", err)
	}

	err = tmpl.Execute(file, vars)

	if err != nil {
		log.Panic("Got error", err)
	}
}
コード例 #5
0
ファイル: packetMaker.go プロジェクト: pee/smapoller
func writePacketLength(dst []byte) error {

	var LENGTH_OFFSET uint = 13
	var LENGTH_HEADER uint = 15
	var MAX_LENGTH uint = 0xFFFF

	if uint(len(dst)) < LENGTH_HEADER {
		log.Panic("Tried to set packet length to short buffer")
	}
	if uint(len(dst)) > MAX_LENGTH {
		log.Panic("Tried to set to big a packet length")
	}

	log.Println("Length of packet is:", len(dst))
	var length uint = uint(len(dst)) - (LENGTH_OFFSET + 7)
	log.Println("Setting packet length to:", length)

	l := make([]byte, 2)
	binary.LittleEndian.PutUint16(l, uint16(length))

	i := LENGTH_OFFSET
	dst[i] = l[0]
	i++
	dst[i] = l[1]

	return nil
}
コード例 #6
0
ファイル: riak_node.go プロジェクト: sargun/riak-mesos
func (riakNode *RiakNode) configureRiak(ports chan int64) templateData {

	data, err := Asset("data/riak.conf")
	if err != nil {
		log.Panic("Got error", err)
	}
	tmpl, err := template.New("test").Parse(string(data))

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

	// Populate template data from the MesosTask
	vars := templateData{}
	vars.FullyQualifiedNodeName = riakNode.taskData.FullyQualifiedNodeName

	vars.HTTPPort = <-ports
	vars.PBPort = <-ports
	vars.HandoffPort = <-ports
	vars.DisterlPort = <-ports

	file, err := os.OpenFile("riak/riak/etc/riak.conf", os.O_TRUNC|os.O_CREATE|os.O_RDWR, 0664)

	defer file.Close()
	if err != nil {
		log.Panic("Unable to open file: ", err)
	}

	err = tmpl.Execute(file, vars)

	if err != nil {
		log.Panic("Got error", err)
	}
	return vars
}
コード例 #7
0
ファイル: db.go プロジェクト: oceandiver/firstgo
func init() {
	dbUrl := os.Getenv("DATABASE_URL")
	if dbUrl == "" {
		log.Panic("Missing required environment variable 'DATABASE_URL'.")
	}

	db, err := sql.Open("postgres", dbUrl)
	fmt.Println("dbUrl", dbUrl)
	checkErr(err)
	if nil != err {
		log.WithFields(log.Fields{
			"error": err,
		}).Fatal("Database connection error")
		log.Panic("failed to open db")
	}

	dbmap = &gorp.DbMap{
		Db:      db,
		Dialect: gorp.PostgresDialect{},
	}

	if os.Getenv("DEBUG") == "true" {
		dbmap.TraceOn("[gorp]", stdlog.New(os.Stdout, "authentication:", stdlog.Lmicroseconds))
	}

	t := dbmap.AddTableWithName(User{}, "users").SetKeys(true, "Id")
	log.Info(t)
	t = dbmap.AddTableWithName(Event{}, "events").SetKeys(true, "Id")
	log.Info(t)
	t = dbmap.AddTableWithName(Attendance{}, "attendance")
	log.Info(t)

	mydb = db

}
コード例 #8
0
ファイル: collector.go プロジェクト: mcmillan/socialite
func Run() {
	sinceID, err := store.SinceID()

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

	store.Expire()

	statuses, err := twitter.GetListStatuses(sinceID)

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

	for index, status := range statuses {
		if index == 0 {
			store.SetSinceID(status.ID)
		}

		for _, url := range status.Entities.URLs {
			link, err := metadata.ParseURL(url.ExpandedURL)

			if err != nil {
				log.Error(err)
				continue
			}

			store.Add(link)
		}
	}
}
コード例 #9
0
func (re *RiakExplorer) configure(port int64, nodename string) {
	data, err := Asset("riak_explorer.conf")
	if err != nil {
		log.Panic("Got error", err)
	}
	tmpl, err := template.New("test").Parse(string(data))

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

	// Populate template data from the MesosTask
	vars := templateData{}

	vars.NodeName = nodename
	vars.HTTPPort = port
	configpath := filepath.Join(".", "riak_explorer", "riak_explorer", "etc", "riak_explorer.conf")
	file, err := os.OpenFile(configpath, os.O_TRUNC|os.O_CREATE|os.O_RDWR, 0)

	defer file.Close()
	if err != nil {
		log.Panic("Unable to open file: ", err)
	}

	err = tmpl.Execute(file, vars)

	if err != nil {
		log.Panic("Got error", err)
	}
}
コード例 #10
0
ファイル: main.go プロジェクト: leominov/udp-test
func main() {
	var (
		laddr  *net.UDPAddr
		mcaddr *net.UDPAddr

		conn  *net.UDPConn
		lconn *net.UDPConn

		err error
	)

	laddr, err = net.ResolveUDPAddr("udp", ":0")
	if err != nil {
		logrus.Panicf("Error resolving UDP address with %v", err)
	}

	mcaddr, err = net.ResolveUDPAddr("udp", "239.255.2.122:1234")
	if err != nil {
		logrus.Panicf("Error resolving UDP address with %v", err)
	}

	conn, err = net.ListenMulticastUDP("udp", nil, mcaddr)
	if err != nil {
		logrus.Panic(err)
	}

	lconn, err = net.ListenUDP("udp", laddr)
	if err != nil {
		logrus.Panic(err)
	}

	go listen(conn)
	go write(conn, lconn, mcaddr)
}
コード例 #11
0
// GenerateDefaultTLS will generate a certificate and a private key, on-the-fly
// This certificate will not be persistant (until you save it yourself)
// This is made by design to generate a new certificate at each server start, if you
// don't provide one yourself
func GenerateDefaultTLS(certPath string, keyPath string) (cert []byte, key []byte) {
	log.Info("Generating TLS certificate and key")

	rootName := "itsyou.online"
	priv, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)

	if err != nil {
		log.Panic("Failed to generate private key: ", err)
	}

	notBefore := time.Now()
	notAfter := notBefore.Add(4 * 365 * 24 * time.Hour) // 4 years

	serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
	serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
	if err != nil {
		log.Panic("Failed to generate serial number: ", err)
	}

	template := x509.Certificate{
		SerialNumber: serialNumber,
		Subject: pkix.Name{
			Country:      []string{"Belgium"},
			Locality:     []string{"Lochristi"},
			Organization: []string{"It's You Online"},
			CommonName:   rootName,
		},
		NotBefore: notBefore,
		NotAfter:  notAfter,

		KeyUsage:              x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
		BasicConstraintsValid: true,

		DNSNames: []string{rootName},
	}

	derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
	if err != nil {
		log.Panic("Failed to create certificate: ", err)
	}

	// Certificates output (in memory)

	var certOut, keyOut bytes.Buffer

	pem.Encode(&certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})

	b, err := x509.MarshalECPrivateKey(priv)
	if err != nil {
		log.Panic("Unable to marshal ECDSA private key: ", err)
	}

	pemUnmarsh := pem.Block{Type: "EC PRIVATE KEY", Bytes: b}

	pem.Encode(&keyOut, &pemUnmarsh)

	return certOut.Bytes(), keyOut.Bytes()
}
コード例 #12
0
ファイル: https.go プロジェクト: itsyouonline/identityserver
func PrepareHTTPS(s *http.Server, cert string, key string, skipDev bool) error {
	// Checking for TLS default keys
	var certBytes, keyBytes []byte

	devCert := "devcert/cert.pem"
	devKey := "devcert/key.pem"

	// If only a single argument is set
	if (cert == "" || key == "") && (cert != "" || key != "") {
		log.Panic("You cannot specify only key or certificate")
	}

	// Using default certificate
	if cert == "" && !skipDev {
		if _, err := os.Stat(devCert); err == nil {
			if _, err := os.Stat(devKey); err == nil {
				log.Warning("===============================================================================")
				log.Warning("This instance will use development certificates, don't use them in production !")
				log.Warning("===============================================================================")

				cert = devCert
				key = devKey

			} else {
				log.Debug("No devcert key found: ", devKey)
			}

		} else {
			log.Debug("No devcert certificate found: ", devCert)
		}
	}

	if _, err := os.Stat(cert); err != nil {
		if _, err := os.Stat(key); err != nil {
			certBytes, keyBytes = GenerateDefaultTLS(cert, key)
		}

	} else {
		log.Info("Loading TLS Certificate: ", cert)
		log.Info("Loading TLS Private key: ", key)

		certBytes, err = ioutil.ReadFile(cert)
		keyBytes, err = ioutil.ReadFile(key)
	}

	certifs, err := tls.X509KeyPair(certBytes, keyBytes)
	if err != nil {
		log.Panic("Cannot parse certificates")
	}

	s.TLSConfig = &tls.Config{
		Certificates: []tls.Certificate{certifs},
	}

	return nil
}
コード例 #13
0
ファイル: guardian.go プロジェクト: suricatatalk/guardian
func main() {
	//TODO os.Getenv("DOMAIN")
	configureSocial()
	// Load all configuration
	appCfg = &AppConfig{}
	mgoCfg := &MgoConfig{}
	natsCfg := &NatsConfig{}
	loadConfiguration(appCfg, mgoCfg, natsCfg)

	log.Infoln("Initializing NatsMailClient")
	initMail()
	var mailErr error
	mailClient, mailErr = client.NewNatsMailClient(natsCfg.Endpoint)
	if mailErr != nil {
		log.Errorf("Cannot initialize mail client: %s", mailErr.Error())
	}
	//Mongo configuration
	log.Infoln("Loading configuration of MongoDB")
	mgoStorage := auth.NewMgoStorage()
	mgoStorage.ConnectionString = mgoCfg.URI
	mgoStorage.Database = mgoCfg.DB
	err := mgoStorage.OpenSession()
	if err != nil {
		log.Panic(err)
	}
	log.Infoln("Initializing auth provider")
	mgoAuthProvider := auth.NewAuthProvider(mgoStorage)
	authProvider = mgoAuthProvider
	passManager = mgoAuthProvider

	log.Infoln("Initializing reverse proxy")

	log.Infoln("Registering handlers")
	//Handle login and register

	clientConn, _ := nats.Connect(natsCfg.Endpoint)
	defer clientConn.Close()
	mux, natsErr := natsproxy.NewNatsClient(clientConn)
	if natsErr != nil {
		log.Panic("Cannot initialize NATS client")
	}
	mux.GET("/activate/:activateToken", activateHandler)
	mux.POST("/login", loginHandler)
	mux.POST("/register", registerHandler)

	mux.POST("/requestpasswordreset", requestPasswordResetHandler)
	mux.POST("/resetpassword/:resettoken", passwordResetHandler)
	// mux.Get("/auth/{provider}/callback", handleSocialLogin)
	// mux.Get("/auth/{provider}", gothic.BeginAuthHandler)
	//else handle via proxy

	sig := make(chan os.Signal, 1)
	signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
	fmt.Println("Press Ctrl+C for exit.")
	<-sig
}
コード例 #14
0
ファイル: cepm.go プロジェクト: sargun/riak-mesos
func (c *CEPM) GetPort() int {
	_, strPort, err := net.SplitHostPort(c.ln.Addr().String())
	if err != nil {
		log.Panic(err)
	}
	port, err := strconv.Atoi(strPort)
	if err != nil {
		log.Panic(err)
	}
	return port
}
コード例 #15
0
ファイル: logsegment.go プロジェクト: andew42/brightlight
// Constructor
func NewLogSegment(baseSeg Segment, start uint, len uint) LogSegment {

	baseLen := baseSeg.Len()
	if start >= baseLen {
		log.Panic("invalid segment start")
	}
	if start+len > baseLen {
		log.Panic("invalid segment length")
	}
	return LogSegment{baseSeg, start, len}
}
コード例 #16
0
ファイル: framework.go プロジェクト: sanmiguel/riak-mesos
func (mgr *MetadataManager) SetupFramework(URI string) {
	err := mgr.zkLock.Lock()
	if err != nil {
		log.Panic("Unable to get framework lock: ", err)
	}
	URIPath := makeSubSpace(mgr.namespace, "uri")
	_, err = mgr.zkConn.Create(URIPath.GetZKPath(), []byte(URI), zk.FlagEphemeral, zk.WorldACL(zk.PermAll))
	if err != nil {
		log.Panic(err)
	}

}
コード例 #17
0
ファイル: tools.go プロジェクト: glickbot/riak-mesos
func zkGetData() string {
	conn, _, err := zk.Connect([]string{zookeeperAddr}, time.Second)
	if err != nil {
		log.Panic(err)
	}
	data, _, err := conn.Get(frameworkName)

	if err != nil {
		log.Panic(err)
	}
	return string(data)
}
コード例 #18
0
ファイル: tools.go プロジェクト: glickbot/riak-mesos
func zkListChildren() []string {
	conn, _, err := zk.Connect([]string{zookeeperAddr}, time.Second)
	if err != nil {
		log.Panic(err)
	}
	children, _, err := conn.Children(frameworkName)

	if err != nil {
		log.Panic(err)
	}
	return children
}
コード例 #19
0
ファイル: gate.go プロジェクト: suricatatalk/gate
func main() {
	//TODO os.Getenv("DOMAIN")
	configureSocial()
	// Load all configuration
	appCfg = &AppConfig{}
	rdisCfg := &RedisConfig{}
	natsCfg := &NatsConfig{}
	loadConfiguration(appCfg, rdisCfg, natsCfg)

	//Mongo configuration
	log.Infoln("Loading configuration of Redis")
	rdisStorage := storage.NewRedisStorage()
	rdisStorage.URL = rdisCfg.URI
	rdisStorage.Password = rdisCfg.Password
	rdisStorage.Database = rdisCfg.DB
	tokenStorage = rdisStorage
	err := tokenStorage.OpenSession()
	defer tokenStorage.CloseSession()
	if err != nil {
		log.Panic(err)
	}

	log.Infoln("Initializing NATS proxy")
	proxyConn, _ := nats.Connect(natsCfg.Endpoint)
	multiProxy, err := natsproxy.NewNatsProxy(proxyConn)
	multiProxy.AddHook("/login.*", loginHook)
	defer proxyConn.Close()
	if err != nil {
		log.Panic("Cannot initialize NATS proxy")
	}

	log.Infoln("Registering handlers")
	//Handle login and register
	mux := http.NewServeMux()
	log.Infoln("Start listening on " + appCfg.Port)
	mux.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) {
		log.Println("Handling")
		transformToken(req)
		log.Println(req.Header)
		multiProxy.ServeHTTP(rw, req)
	})

	//Init HTTP2 server
	srv := &http.Server{
		Addr:    ":" + appCfg.Port,
		Handler: mux,
	}
	http2.ConfigureServer(srv, nil)
	serveErr := srv.ListenAndServe()
	if serveErr != nil {
		log.Errorln(serveErr)
	}
}
コード例 #20
0
ファイル: auth.go プロジェクト: oceandiver/firstgo
func init() {
	authKey := os.Getenv("AUTH_KEY")
	if authKey == "" {
		log.Panic("Missing required environment variable 'AUTH_KEY'.")
	}

	encryptKey := os.Getenv("ENCRYPT_KEY")
	if encryptKey == "" {
		log.Panic("Missing required environment variable 'ENCRYPT_KEY' (16, 24, 32 bytes in length).")
	}

	store = sessions.NewCookieStore([]byte(authKey), []byte(encryptKey))
}
コード例 #21
0
ファイル: state.go プロジェクト: sanmiguel/riak-mesos
func DeserializeSchedulerState(data []byte) (*SchedulerState, error) {
	r, err := zlib.NewReader(bytes.NewBuffer(data))
	if err != nil {
		log.Panic(err)
	}
	decoder := json.NewDecoder(r)
	t := &SchedulerState{}
	err = decoder.Decode(&t)
	if err != nil {
		log.Panic(err)
	}
	return t, err
}
コード例 #22
0
ファイル: metadata_manager.go プロジェクト: sargun/riak-mesos
func (mgr *MetadataManager) getChildren(ns Namespace) []*ZkNode {
	children, _, err := mgr.zkConn.Children(ns.GetZKPath())
	if err != nil {
		log.Panic(err)
	}
	result := make([]*ZkNode, len(children))
	for idx, name := range children {
		result[idx], err = mgr.getNode(makeSubSpace(ns, name))
		if err != nil {
			log.Panic(err)
		}
	}
	return result
}
コード例 #23
0
ファイル: email.go プロジェクト: tomyhero/billie
func (self *Email) Notify(body string, attachments [][]*multipart.FileHeader) {

	m := gomail.NewMessage()
	m.SetHeader("From", self.From)

	m.SetHeader("To", strings.Split(self.To, ",")...)

	if self.CC != "" {
		m.SetHeader("CC", strings.Split(self.CC, ",")...)
	}

	m.SetHeader("Subject", self.Title)
	m.SetBody(self.ContentType, body)

	for _, tmp := range attachments {
		for _, attachment := range tmp {
			f, err := attachment.Open()
			if err != nil {
				log.Panic(err)
			}

			defer f.Close()
			m.Attach(attachment.Filename,
				gomail.SetCopyFunc(func(w io.Writer) error {
					_, err := io.Copy(w, f)
					return err
				}),
			)
		}
	}

	port, err := strconv.Atoi(self.SMTP["port"].(string))

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

	d := gomail.NewPlainDialer(
		self.SMTP["host"].(string),
		port,
		self.SMTP["user"].(string),
		self.SMTP["password"].(string),
	)

	// Send the email to Bob, Cora and Dan.
	if err := d.DialAndSend(m); err != nil {
		log.Panic(err)
	}

}
コード例 #24
0
ファイル: 07_web_server.go プロジェクト: niukey/learn
func main() {
	lf, err := openToAppend(logPath)
	if err != nil {
		log.Panic(err)
	}
	defer lf.Close()
	log.SetOutput(lf)

	rootContext := context.Background()
	// rootContext = context.WithValue(rootContext, dbKey, db)

	mainRouter := http.NewServeMux()
	mainRouter.Handle("/", &ContextAdapter{
		ctx:     rootContext,
		handler: ContextHandlerFunc(handlerRoot),
	})
	mainRouter.Handle("/sendjson", &ContextAdapter{
		ctx:     rootContext,
		handler: ContextHandlerFunc(handlerSendJSON),
	})
	mainRouter.Handle("/sendgob", &ContextAdapter{
		ctx:     rootContext,
		handler: ContextHandlerFunc(handlerSendGOB),
	})
	mainRouter.Handle("/hello", &ContextAdapter{
		ctx:     rootContext,
		handler: ContextHandlerFunc(handlerHello),
	})
	mainRouter.Handle("/photo", &ContextAdapter{
		ctx:     rootContext,
		handler: ContextHandlerFunc(handlerPhoto),
	})
	mainRouter.Handle("/json", &ContextAdapter{
		ctx:     rootContext,
		handler: ContextHandlerFunc(handlerJSON),
	})
	mainRouter.Handle("/gob", &ContextAdapter{
		ctx:     rootContext,
		handler: ContextHandlerFunc(handlerGOB),
	})

	// func (mux *ServeMux) Handle(pattern string, handler Handler)
	mainRouter.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))

	fmt.Println("Serving http://localhost" + port)
	log.Infoln("Server started at", port)
	if err := http.ListenAndServe(port, wrapRouterWithLogrus(mainRouter)); err != nil {
		log.Panic(err)
	}
}
コード例 #25
0
ファイル: metadata_manager.go プロジェクト: sargun/riak-mesos
// This subspaces the node in the "current working namespace"
func (mgr *MetadataManager) GetRootNode() *ZkNode {
	node, err := mgr.getNode(mgr.namespace)
	if err != nil {
		log.Panic("Could not get Root node")
	}
	return node
}
コード例 #26
0
ファイル: graph.go プロジェクト: shaunstanislaus/go-torch
// pathAsString takes a path and a mapping of node names to node structs and
// generates the string representation of the path expected by the
// visualization package.
func (p *defaultPathStringer) pathAsString(path []ggv.Edge, nameToNodes map[string]*ggv.Node) string {
	var (
		pathBuffer bytes.Buffer
		weightSum  int
	)
	for _, edge := range path {
		// If the function call represented by the edge happened very rarely,
		// the edge's weight will not be recorded. The edge's label will always
		// be recorded.
		if weightStr, ok := edge.Attrs["weight"]; ok {
			weight, err := strconv.Atoi(weightStr)
			if err != nil { // This should never happen
				log.Panic(err)
			}
			weightSum += weight
		}
		functionLabel := getFormattedFunctionLabel(nameToNodes[edge.Src])
		pathBuffer.WriteString(functionLabel + ";")
	}
	if len(path) >= 1 {
		lastEdge := path[len(path)-1]
		lastFunctionLabel := getFormattedFunctionLabel(nameToNodes[lastEdge.Dst])
		pathBuffer.WriteString(lastFunctionLabel + " ")
	}
	pathBuffer.WriteString(fmt.Sprint(weightSum))
	pathBuffer.WriteString("\n")

	return pathBuffer.String()
}
コード例 #27
0
ファイル: 02_logrus.go プロジェクト: agupt/learn
func main() {
	lf, err := openToAppend("my.log")
	if err != nil {
		panic(err)
	}
	defer lf.Close()
	// Output to stderr instead of stdout, could also be a file.
	log.SetOutput(lf)

	log.Println("Hello World!") // Println belongs to Infoln
	log.WithFields(log.Fields{
		"animal": "walrus",
		"size":   10,
	}).Info("A group of walrus emerges from the ocean")

	log.WithFields(log.Fields{
		"omg":    true,
		"number": 122,
	}).Warn("The group's number increased tremendously!")

	log.Panic("panic")

	log.WithFields(log.Fields{
		"omg":    true,
		"number": 100,
	}).Panic("The ice breaks!")
}
コード例 #28
0
ファイル: executor.go プロジェクト: glickbot/riak-mesos
func (exec *ExecutorCore) LaunchTask(driver exec.ExecutorDriver, taskInfo *mesos.TaskInfo) {
	exec.lock.Lock()
	defer exec.lock.Unlock()
	fmt.Println("Launching task", taskInfo.GetName(), "with command", taskInfo.Command.GetValue())
	os.Args[0] = fmt.Sprintf("executor - %s", taskInfo.TaskId.GetValue())

	//fmt.Println("Other hilarious facts: ", taskInfo)

	//
	// this is where one would perform the requested task
	//
	fmt.Println("Starting task")

	runStatus := &mesos.TaskStatus{
		TaskId: taskInfo.TaskId,
		State:  mesos.TaskState_TASK_STARTING.Enum(),
	}
	_, err := driver.SendStatusUpdate(runStatus)

	if err != nil {
		log.Panic("Got error", err)
	}

	if exec.riakNode != nil {
		log.Fatalf("Task being started, twice, existing task: %+v, new task: %+v", exec.riakNode)
	}
	exec.riakNode = NewRiakNode(taskInfo, exec)
	exec.riakNode.Run()

}
コード例 #29
0
ファイル: scheduler.go プロジェクト: sanmiguel/riak-mesos
func (sc *SchedulerCore) acceptOffer(driver sched.SchedulerDriver, offer *mesos.Offer, operations []*mesos.Offer_Operation) {
	log.Infof("Accepting OfferID: %+v, Operations: %+v", *offer.Id.Value, operations)

	var status mesos.Status
	var err error

	if sc.compatibilityMode {
		tasks := []*mesos.TaskInfo{}
		for _, operation := range operations {
			if *operation.Type == mesos.Offer_Operation_LAUNCH {
				tasks = operation.Launch.TaskInfos
			}
		}
		status, err = driver.LaunchTasks([]*mesos.OfferID{offer.Id}, tasks, &mesos.Filters{RefuseSeconds: proto.Float64(OFFER_INTERVAL)})
	} else {
		status, err = driver.AcceptOffers([]*mesos.OfferID{offer.Id}, operations, &mesos.Filters{RefuseSeconds: proto.Float64(OFFER_INTERVAL)})
	}

	if status != mesos.Status_DRIVER_RUNNING {
		log.Fatal("Driver not running, while trying to accept offers")
	}
	if err != nil {
		log.Panic("Failed to launch tasks: ", err)
	}
}
コード例 #30
0
ファイル: cli.go プロジェクト: akutz/rexray
// Execute executes the CLI.
func (c *CLI) Execute() {

	defer func() {
		if c.activateLibStorage {
			util.WaitUntilLibStorageStopped(c.ctx, c.rsErrs)
		}
	}()

	defer func() {
		r := recover()
		switch r := r.(type) {
		case nil:
			return
		case int:
			log.Debugf("exiting with error code %d", r)
			os.Exit(r)
		case error:
			log.Panic(r)
		default:
			log.Debugf("exiting with default error code 1, r=%v", r)
			os.Exit(1)
		}
	}()

	c.execute()
}