Exemple #1
0
func main() {
	var err error

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

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

	UDPConn, err := net.DialUDP("udp", localAddr, serverAddr)
	if err != nil {
		logrus.Panicf("Error with dial UDP: %v", err)
	}

	defer UDPConn.Close()
	readBuf := make([]byte, UDPBufSize)
	for {
		read, err := UDPConn.Read(readBuf)
		if err != nil {
			logrus.Print("Read error: %v", err)
			continue
		}

		logrus.Printf("Readed bytes %d with message: %s", read, string(readBuf))
	}
}
Exemple #2
0
func NewFrameworkRiakNode(sc *SchedulerCore, clusterName string, restartGeneration int64, simpleId int) *FrameworkRiakNode {
	nodeCpusFloat, err := strconv.ParseFloat(sc.nodeCpus, 64)
	if err != nil {
		log.Panicf("Unable to determine node_cpus: %+v", err)
	}
	nodeMemFloat, err := strconv.ParseFloat(sc.nodeMem, 64)
	if err != nil {
		log.Panicf("Unable to determine node_mem: %+v", err)
	}
	nodeDiskFloat, err := strconv.ParseFloat(sc.nodeDisk, 64)
	if err != nil {
		log.Panicf("Unable to determine node_disk: %+v", err)
	}

	return &FrameworkRiakNode{
		DestinationState:  process_state.Started,
		CurrentState:      process_state.Unknown,
		Generation:        0,
		reconciled:        false,
		FrameworkName:     sc.frameworkName,
		Role:              &sc.frameworkRole,
		Principal:         &sc.mesosAuthPrincipal,
		SimpleId:          simpleId,
		ClusterName:       clusterName,
		Cpus:              nodeCpusFloat,
		Mem:               nodeMemFloat,
		Disk:              nodeDiskFloat,
		Ports:             PORTS_PER_TASK,
		UUID:              uuid.NewV4().String(),
		ContainerPath:     CONTAINER_PATH,
		RestartGeneration: restartGeneration,
	}
}
Exemple #3
0
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)
}
Exemple #4
0
func main() {
	var err error

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

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

	UDPConn, err := net.DialUDP("udp", localAddr, serverAddr)
	if err != nil {
		logrus.Panicf("Error with dial UDP: %v", err)
	}

	defer UDPConn.Close()

	i := 0
	for {
		msg := strconv.Itoa(i)
		i++

		buf := []byte(msg)
		_, err := UDPConn.Write(buf)
		if err != nil {
			logrus.Printf("Error with sending message (%s) with %v", msg, err)
		}

		time.Sleep(1 * time.Second)
	}
}
Exemple #5
0
func init() {
	kv, err := kvdb.New(mem.Name, "driver_test", []string{}, nil)
	if err != nil {
		log.Panicf("Failed to intialize KVDB")
	}
	err = kvdb.SetInstance(kv)
	if err != nil {
		log.Panicf("Failed to set KVDB instance")
	}
}
Exemple #6
0
func assertTagged(image string) reference.NamedTagged {
	ref, err := reference.Parse(image)
	if err != nil {
		logrus.Panicf("Invalid reference %q: %v", image, err)
	}
	named, ok := ref.(reference.NamedTagged)
	if !ok {
		logrus.Panicf("Image reference must have name and tag: %s", image)
	}

	return named
}
func init() {
	kv, err := kvdb.New(mem.Name, "driver_test", []string{}, nil)
	if err != nil {
		logrus.Panicf("Failed to intialize KVDB")
	}
	err = kvdb.SetInstance(kv)
	if err != nil {
		logrus.Panicf("Failed to set KVDB instance")
	}

	e = NewDefaultEnumerator("enumerator_test", kv)
}
Exemple #8
0
func DumpStore(dbName string) {

	db, err := bolt.Open(dbName, 0600, &bolt.Options{Timeout: 1 * time.Second})
	if err != nil {
		log.Panicf("unable to open %s, error: %v\n", dbName, err)
	}
	db.View(func(tx *bolt.Tx) error {
		b := tx.Bucket([]byte("events"))
		b.ForEach(func(k, v []byte) error {

			seq, err := readSequence(k)
			if err != nil {
				log.Errorf("Error decoding sequence number %v", err)
			}

			evt, err := decodeEvent(v)
			if err != nil {
				log.Errorf("Error decoding event %v", err)
			}
			body := strings.Replace(string(evt.Body), "\n", "\\n", -1)
			fmt.Printf("key=%d, value={channel:\"%s\", body:\"%s\"}\n", seq, evt.Channel, body)
			return nil
		})
		return nil
	})
}
Exemple #9
0
func GetReader(config []byte) Reader {
	var err error

	br := BaseReader{}
	err = json.Unmarshal(config, &br)
	if err != nil {
		logrus.Error(err)
		logrus.Fatal("Missing reader name and/or type")
	}

	var r Reader

	switch br.Type {
	default:
		logrus.Panicf("Unrecognized reader type: %#v", br)
	case "FileReader":
		fr := FileReader{}
		err = json.Unmarshal(config, &fr)
		r = &fr
	}

	if err != nil {
		logrus.Error(err)
		logrus.Fatal(fmt.Sprintf("Invalid configuration for %#v", br))
	}

	return r
}
Exemple #10
0
func Listening() {
	defer func() {
		if sm.l != nil {
			sm.l.Close()
		}
	}()
	l, err := net.Listen("tcp", sm.config.ProxyPort)
	if err != nil {
		log.Panicf("switch manager Listening panic, err:%s\n", err.Error())
	}
	sm.l = l
	var i = 1
	for {
		sm.rwMutex.RLock()
		if sm.closed {
			sm.rwMutex.RUnlock()
			break
		} else {
			sm.rwMutex.RUnlock()
		}
		conn, err := sm.l.Accept()
		if err != nil {
			log.Errorf("sm.l.Accept error:%+v\n", err.Error())
		} else {
			log.Infof("accept connection count %d\n", i)
			go handleConn(sm, conn)
		}

		i++
	}
}
Exemple #11
0
// Create schema
func createSchema() {
	dbDir := filepath.Dir(*flags.DBPath)
	if _, err := os.Stat(dbDir); os.IsNotExist(err) {
		os.MkdirAll(dbDir, 0777)
		log.Infof("Created directory path=%s", dbDir)
	}
	db, _ := connection()
	defer db.Close()
	stmt, err := db.Prepare(`
		CREATE TABLE notes (
			uid string,
			created string,
			updated string,
			tags string,
			content string,
			encrypted INTEGER DEFAULT 0,
			subject TEXT
		);`)
	if err != nil {
		if err.Error() != "table notes already exists" {
			log.Panicf("Unable to prepare schema path=%s, err=%v", *flags.DBPath, err)
		}
		return
	}
	_, err = stmt.Exec()
	if err != nil {
		log.Errorf("Unable to create schema err=%v", err)
	}
	log.Infof("Schema created path=%s", *flags.DBPath)

}
Exemple #12
0
func main() {
	log.Infof("Starting up Popular DNS for domain `%s`...", config.Domain)

	cfClient, err := cloudflare.NewClient(config.CloudFlareEmail, config.CloudFlareToken)
	if err != nil {
		log.Panicf("Could not create CloudFlare client for email `%s`: %v", config.CloudFlareEmail, err)
	} else {
		cf = cfClient
	}

	record, err := createOrGetRecord(config.Domain, config.Domain)
	if err != nil {
		log.Panic(err)
	} else {
		recordId = record.Id
	}

	store = NewDomainStore(config.FirebaseURL, config.FirebaseAuth)

	http.Handle("/ui/dist/", http.StripPrefix("/ui/dist/", http.FileServer(http.Dir("ui/dist"))))
	http.HandleFunc("/set", set)
	http.HandleFunc("/", view)
	http.ListenAndServe(":8080", nil)

}
Exemple #13
0
func init() {
	configFile := defaultConfigFile
	if configFileEnv := os.Getenv("CONFIG_FILE"); len(configFileEnv) != 0 {
		configFile = configFileEnv
	}

	data, err := ioutil.ReadFile(configFile)
	if err != nil {
		log.Panicf("Could not read configuration file: %v", err)
	}

	err = json.Unmarshal(data, &config)
	if err != nil {
		log.Panicf("Could not unmarshal configuration struct from file `%s`: %v", configFile, err)
	}
}
// Init Refcounts. Discover volume usage refcounts from Docker.
// This functions does not sync with mount/unmount handlers and should be called
// and completed BEFORE we start accepting Mount/unmount requests.
func (r refCountsMap) Init(d *vmdkDriver) {
	c, err := client.NewClient(dockerUSocket, apiVersion, nil, defaultHeaders)
	if err != nil {
		log.Panicf("Failed to create client for Docker at %s.( %v)",
			dockerUSocket, err)
	}
	log.Infof("Getting volume data from %s", dockerUSocket)
	info, err := c.Info(context.Background())
	if err != nil {
		log.Infof("Can't connect to %s, skipping discovery", dockerUSocket)
		// TODO: Issue #369
		// Docker is not running, inform ESX to detach docker volumes, if any
		// d.detachAllVolumes()
		return
	}
	log.Debugf("Docker info: version=%s, root=%s, OS=%s",
		info.ServerVersion, info.DockerRootDir, info.OperatingSystem)

	// connects (and polls if needed) and then calls discovery
	err = r.discoverAndSync(c, d)
	if err != nil {
		log.Errorf("Failed to discover mount refcounts(%v)", err)
		return
	}

	log.Infof("Discovered %d volumes in use.", len(r))
	for name, cnt := range r {
		log.Infof("Volume name=%s count=%d mounted=%t device='%s'",
			name, cnt.count, cnt.mounted, cnt.dev)
	}
}
Exemple #15
0
// connection to a sqlite database (currently hard coded for testing)
func connection() (*sql.DB, error) {
	db, err := sql.Open("sqlite3", *flags.DBPath)
	if err != nil {
		log.Panicf("Unable to open database path=%s, err=%v", *flags.DBPath, err)
	}
	return db, err
}
Exemple #16
0
func getTestDb() *gorm.DB {
	if test_db != nil {
		return test_db
	}
	db, err := gorm.Open("sqlite3", "./api-test.db")

	if err != nil {
		log.Panicf("Error opening sqlite3 database in test %v\n", err)
	}

	db.DropTable(&User{})
	db.DropTable(&PrivateWidget{})
	db.DropTable(&Widget{})
	db.DropTable(&VerifiedWidget{})
	db.CreateTable(&User{})
	db.CreateTable(&PrivateWidget{})
	db.CreateTable(&Widget{})
	db.CreateTable(&VerifiedWidget{})

	var private_widgets []PrivateWidget
	db.Model(&User{}).Related(&private_widgets)

	db.Create(&User{Name: "admin", Password: "******"})

	db.Create(&Widget{ID: 1, Name: "Widget 1"})
	db.Create(&Widget{ID: 2, Name: "Widget 2"})
	db.Create(&Widget{ID: 3, Name: "Widget 3"})

	test_db = &db
	if *verboseMartini {
		test_db = test_db.Debug()
	}
	return test_db
}
Exemple #17
0
func (r *RoundRobinPeerSelector) SetMaxLen(m uint32) {
	if m > math.MaxUint16 {
		log.Panicf("Number of peers %v greater than those suported %v",
			m, math.MaxUint16)
	}
	atomic.StoreUint32(&r.maxLen, m)
}
Exemple #18
0
//InstallDependencies install all external sources
func (b *Base) InstallDependencies() error {
	components := b.MainfileData.Graph
	for _, c := range components {
		if !IsExternal(c) {
			//Save the parameters to the answer data.
			b.updateComponentAnswers(c)
			continue
		}
		logrus.Infof("Installing dependency: %s", c.Name)
		image, err := GetSourceImage(c)
		if err != nil {
			return err
		}
		externalDir, err := b.makeExternalAppDirectory(c)
		if err != nil {
			return err
		}
		externalBase := New(externalDir, image)
		externalBase.setAnswersDir(b.Target())
		if err := externalBase.Install(); err != nil {
			logrus.Panicf("Failed to install dependency: %s", err)
			return err
		}
	}
	return nil
}
// InitConfig initializes configuration file
func InitConfig(filepath string, section string) Config {
	var (
		c               Config
		requiredOptions = []string{"host", "client_token", "client_secret", "access_token"}
		missing         []string
	)

	// Check if filepath is empty
	if filepath == "" {
		filepath = "~/.edgerc"
	}

	// Check if section is empty
	if section == "" {
		section = "default"
	}

	// Tilde seems to be not working when passing ~/.edgerc as file
	// Takes current user and use home dir instead

	path, err := tilde.Expand(filepath)

	if err != nil {
		log.Panicf("Fatal could not find home dir from user: %s \n", err)
	}

	edgerc, err := ini.Load(path)
	if err != nil {
		log.Panicf("Fatal error config file: %s \n", err)
	}
	edgerc.Section(section).MapTo(&c)
	for _, opt := range requiredOptions {
		if !(edgerc.Section(section).HasKey(opt)) {
			missing = append(missing, opt)
		}
	}
	if len(missing) > 0 {
		log.Panicf("Fatal missing required options: %s \n", missing)
	}
	if c.MaxBody == 0 {
		c.MaxBody = 131072
	}
	return c
}
func (pm *ProcessManager) doStart(executablePath string, args []string, procattr *syscall.ProcAttr) {
	var err error
	log.Infof("Getting Ready to start process: %v with args: %v and ProcAttr: %+v", executablePath, args, procattr)
	pm.pid, err = syscall.ForkExec(executablePath, args, procattr)
	if err != nil {
		log.Panicf("Error starting process %v", err)
	} else {
		log.Infof("Process Manager started to manage %v at PID: %v", executablePath, pm.pid)
	}
}
func enableHealthchecks(port int) {

	healthcheck := &Healthcheck{http.Client{}, appConfig}
	router := mux.NewRouter()
	router.HandleFunc("/__health", healthcheck.checkHealth())
	router.HandleFunc("/__gtg", healthcheck.gtg)
	http.Handle("/", router)
	err := http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
	if err != nil {
		log.Panicf("Couldn't set up HTTP listener: %+v\n", err)
	}
}
Exemple #22
0
func main() {
	var err error

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

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

	proxy, err := NewUDPProxy(frontendAddr, backendAddr)
	if err != nil {
		logrus.Panicf("Error with creating proxy layout: %v", err)
	}

	logrus.Printf("Listening on %s", proxy.FrontendAddr().String())

	defer proxy.Close()
	proxy.Run()
}
Exemple #23
0
func (ro *RouteOptions) Initialise(g *Grapi) {
	// This could get expensive - just do it once.
	if ro.initialised {
		return
	}
	ro.initialised = true
	if !ro.UseDefaultAuth {
		return
	}
	if ro.Authenticate != nil {
		log.Panicf("Should set either RouteOptions.Authenticate or RouteOptions.UseDefaultAuth, but not both. " +
			"Your custom authenticator will now be overwritten.")
	}
	ro.Authenticate = g.defaultAuthenticator()
}
Exemple #24
0
func main() {
	var (
		backendAddr *net.UDPAddr
		err         error
	)

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

	if err = serveMulticastUDP(backendAddr); err != nil {
		logrus.Errorf("Error service: %v", err)
	}
}
Exemple #25
0
func init() {
	authParts = make(map[string]string)
	// get from address
	fromEmail = os.Getenv("EMAIL_FROM")
	if fromEmail == "" {
		log.Panic("Missing required environment variable 'EMAIL_FROM'.")
	}

	// initialize smtp auth
	for _, part := range []string{"EMAIL_HOST_USER", "EMAIL_HOST_PASSWORD", "EMAIL_HOST", "EMAIL_PORT"} {
		envPart := os.Getenv(part)
		if envPart == "" {
			log.Panicf("Missing required environment variable '%s'.", part)
		}
		authParts[part] = envPart
	}
	auth = smtp.PlainAuth("", authParts["EMAIL_HOST_USER"], authParts["EMAIL_HOST_PASSWORD"], authParts["EMAIL_HOST"])
}
// decr recfcount for the volume vol and returns the new count
// returns -1  for error (and resets count to 0)
// also deletes the node from the map if refcount drops to 0
func (r refCountsMap) decr(vol string) (uint, error) {
	rc := r[vol]
	if rc == nil {
		return 0, fmt.Errorf("decr: refcount is already 0. name=%s", vol)
	}

	if rc.count == 0 {
		// we should NEVER get here. Even if Docker sends Unmount before Mount,
		// it should be caught in previous check. So delete the entry (in case
		// someone upstairs does 'recover', and panic.
		delete(r, vol)
		log.Panicf("decr: refcnt corruption (rc.count=0), name=%s", vol)
	}

	rc.count--
	if rc.count == 0 {
		defer delete(r, vol)
	}
	return rc.count, nil
}
Exemple #27
0
// Parse is converts the input data into html.
func (h *HTML) Parse(f []Field) string {
	t := defaultTemplate

	if h.Template != "" {
		// template check
		_, err := os.Stat(h.Template)
		if err == nil {
			t = template.Must(template.New(filepath.Base(h.Template)).Funcs(template.FuncMap(fns)).ParseFiles(h.Template))
		} else {
			log.Warnf("template does not exist: %s, stat error: %v", h.Template, err)
		}
	}

	var buffer bytes.Buffer
	err := t.Execute(&buffer, map[string]interface{}{"fields": f})
	if err != nil {
		log.Panicf("execute template error: %v", err)
	}

	return buffer.String()
}
func (hh *httpHandlers) idsHandler(w http.ResponseWriter, r *http.Request) {

	idService, ok := hh.s.(rwapi.IDService)
	if !ok {
		w.WriteHeader(http.StatusNotImplemented)
		return
	}

	w.Header().Add("Content-Type", "application/json")

	enc := json.NewEncoder(w)

	err := idService.IDs(func(id rwapi.IDEntry) (bool, error) {
		if err := enc.Encode(id); err != nil {
			return false, err
		}
		return true, nil
	})

	if err != nil {
		log.Errorf(err.Error())

		// at this point, the best we can do is close the connection to inform
		// the client of the error, because we've already said "200"
		conn, _, err := w.(http.Hijacker).Hijack()
		if err != nil {
			// there is very little we can do here. Since we're in an http
			// handler, panic is okay. It will be recovered from and will
			// not crash the application, but at least we will capture the
			// cause.
			log.Panicf(err.Error())
		}
		conn.Close()
	}

	return
}
Exemple #29
0
func (u *user) ProcessEvent(event cells.Event) error {
	switch event.Topic() {
	case SAYS_TO:
		to, ok := event.Payload().Get("to")
		if !ok || to.(string) != makeUserID(u.name) {
			return nil
		}
		log.Info(event.Payload())
	case SAY:
		env := u.ctx.Environment()
		roomID, _ := event.Payload().Get("room")

		if !env.HasCell(roomID.(string)) {
			log.Panicf("%s not found", roomID)
			return fmt.Errorf("room %s not found", roomID)
		}

		ok, err := env.Request(roomID.(string), IN_ROOM, cells.PayloadValues{"user": makeUserID(u.name)}, nil, time.Second)

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

		if !ok.(bool) {
			return fmt.Errorf("%s is not in %s", u.name, roomID)
		}

		payload := event.Payload()
		payload = payload.Apply(cells.PayloadValues{"from": makeUserID(u.name)})

		env.EmitNew(roomID.(string), SAYS_ALL, payload, nil)
	case USER_DISCONNECTED:
		log.Info(USER_DISCONNECTED)
	}
	return nil
}
func (frn *FrameworkRiakNode) NeedsToBeScheduled() bool {
	// Poor man's FSM:
	// TODO: Fill out rest of possible states

	switch frn.DestinationState {
	case process_state.Started:
		{
			switch frn.CurrentState {
			case process_state.Started:
				return false
			case process_state.Unknown:
				return false
			case process_state.Starting:
				return false
			case process_state.Shutdown:
				return true
			case process_state.Failed:
				return true
			}
		}
	}
	log.Panicf("Hit unknown, Current State: (%v), Destination State: (%v)", frn.CurrentState, frn.DestinationState)
	return false
}