Ejemplo n.º 1
30
func messageListener(o *gomegle.Omegle, logger *log.Logger) {
	for {
		err := o.ShowTyping()
		if err != nil {
			logger.Print(err)
		}

		reader := bufio.NewReader(os.Stdin)
		text, err := reader.ReadString('\n')
		if err != nil {
			err = o.Disconnect()
			if err != nil {
				logger.Fatal(err)
			}
			fmt.Println("- Disconnected")
			ret := o.GetID()
			if ret != nil {
				logger.Fatal(ret)
			}
			continue
		}

		err = o.StopTyping()
		if err != nil {
			logger.Print(err)
		}

		err = o.SendMessage(text)
		if err != nil {
			logger.Fatal(err)
			continue
		}
	}
}
Ejemplo n.º 2
0
func broadcastServer(conn *net.UDPConn, port string, sendChannel chan UDPMessage, networkLogger log.Logger) {
	networkLogger.Printf("Broadcasting to port %s", port)
	baddr, err := net.ResolveUDPAddr("udp", "255.255.255.255:"+port)
	if err != nil {
		networkLogger.Fatal(err)
	}

	for {
		message := <-sendChannel
		conn.WriteToUDP(message.Data, baddr)
	}
}
Ejemplo n.º 3
0
func main() {
	var err error
	var stdout []byte
	var ps *exec.Cmd = exec.Command("ps", "aux")
	var log *logging.Logger = logging.New(os.Stderr, "",
		logging.LstdFlags|logging.Lshortfile)

	stdout, err = ps.Output()
	if err != nil {
		log.Fatal(err)
	}

	log.Println(string(stdout))
}
Ejemplo n.º 4
0
Archivo: forward.go Proyecto: kiyoto/ik
func newForwardInput(factory *ForwardInputFactory, logger *log.Logger, bind string, port ik.Port) (*ForwardInput, error) {
	_codec := codec.MsgpackHandle{}
	_codec.MapType = reflect.TypeOf(map[string]interface{}(nil))
	_codec.RawToString = false
	listener, err := net.Listen("tcp", bind)
	if err != nil {
		logger.Fatal(err.Error())
		return nil, err
	}
	return &ForwardInput{
		factory:  factory,
		port:     port,
		logger:   logger,
		bind:     bind,
		listener: listener,
		codec:    &_codec,
		running:  false,
		clients:  make(map[net.Conn]*forwardClient),
	}, nil
}
Ejemplo n.º 5
0
// Initialise a JarvisBot.
// lg is optional.
func InitJarvis(name string, bot *telebot.Bot, lg *log.Logger, config map[string]string) *JarvisBot {
	// We'll use random numbers throughout JarvisBot
	rand.Seed(time.Now().UTC().UnixNano())

	if lg == nil {
		lg = log.New(os.Stdout, "[jarvis] ", 0)
	}
	j := &JarvisBot{Name: name, bot: bot, log: lg, keys: config}

	j.fmap = j.getDefaultFuncMap()

	// Setup database
	// Get current executing folder
	pwd, err := osext.ExecutableFolder()
	if err != nil {
		lg.Fatalf("cannot retrieve present working directory: %s", err)
	}

	db, err := bolt.Open(path.Join(pwd, "jarvis.db"), 0600, nil)
	if err != nil {
		lg.Fatal(err)
	}
	j.db = db
	createAllBuckets(db)

	// Ensure temp directory is created.
	// This is used to store media temporarily.
	tmpDirPath := filepath.Join(pwd, TEMPDIR)
	if _, err := os.Stat(tmpDirPath); os.IsNotExist(err) {
		j.log.Printf("[%s] creating temporary directory", time.Now().Format(time.RFC3339))
		mkErr := os.Mkdir(tmpDirPath, 0775)
		if mkErr != nil {
			j.log.Printf("[%s] error creating temporary directory\n%s", time.Now().Format(time.RFC3339), err)
		}
	}

	return j
}
Ejemplo n.º 6
0
// Initialise a MorningBot.
// lg is optional.
func InitMorningBot(name string, bot *telebot.Bot, lg *log.Logger, config map[string]string) *MorningBot {
	if lg == nil {
		lg = log.New(os.Stdout, "[morningbot] ", 0)
	}
	m := &MorningBot{Name: name, bot: bot, log: lg, keys: config}

	m.fmap = m.getDefaultFuncMap()

	// Setup database
	// Get current executing folder
	pwd, err := osext.ExecutableFolder()
	if err != nil {
		lg.Fatalf("cannot retrieve present working directory: %s", err)
	}

	db, err := bolt.Open(path.Join(pwd, "morningbot.db"), 0600, nil)
	if err != nil {
		lg.Fatal(err)
	}
	m.db = db
	createAllBuckets(db)

	return m
}
Ejemplo n.º 7
0
func processDIR(logger *log.Logger, wg *sync.WaitGroup, fullPath, relPath string, out chan<- []byte, semaphore chan struct{}) {
	defer wg.Done()

	// 1 for "test", 4 for coermode, coverprofile, outputdir, relpath
	args := make([]string, 1, 1+len(flag.Args())+4)
	args[0] = "test"
	args = append(args, flag.Args()...)
	args = append(args, "-covermode="+coverFlag, "-coverprofile="+pkgFilename, "-outputdir="+fullPath+"/", relPath)
	fmt.Printf("Test args: %+v\n", args)

	cmd := exec.Command("go", args...)
	if debugFlag {
		logger.Println("Processing:", strings.Join(cmd.Args, " "))
	}
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		logger.Fatal("Unable to get process stdout")
	}
	go scanOutput(stdout, logger.Print)

	stderr, err := cmd.StderrPipe()
	if err != nil {
		logger.Fatal("Unable to get process stderr")
	}
	go scanOutput(stderr, logger.Print)

	if err := cmd.Run(); err != nil {
		logger.Fatal("ERROR:", err)
	}

	b, err := ioutil.ReadFile(relPath + "/profile.coverprofile")
	if err != nil {
		logger.Fatal("ERROR:", err)
	}

	out <- b

	if isLimited {
		<-semaphore
	}
}
Ejemplo n.º 8
0
func getPort(logger *log.Logger) int {
	configPath := os.Getenv("CONFIG_PATH")
	if configPath == "" {
		return defaultPort
	}

	configBytes, err := ioutil.ReadFile(configPath)
	if err != nil {
		logger.Fatal(err)
	}

	var config config
	err = yaml.Unmarshal(configBytes, &config)
	if err != nil {
		logger.Fatal(err)
	}

	if config.Port == 0 {
		logger.Fatal("Port must be set")
	}

	return config.Port
}
Ejemplo n.º 9
0
func testFiles(logger *log.Logger) {

	var semaphore chan struct{}

	if isLimited {
		semaphore = make(chan struct{}, concurrencyFlag)
	}

	out := make(chan []byte)
	wg := &sync.WaitGroup{}

	walker := func(path string, info os.FileInfo, err error) error {

		if !info.IsDir() {
			return nil
		}

		rel := strings.Replace(path, projectPath, "", 1)

		if _, ignore := ignores[rel]; ignore {
			return filepath.SkipDir
		}

		rel = "./" + rel

		if files, err := filepath.Glob(rel + "/*_test.go"); len(files) == 0 || err != nil {

			if err != nil {
				logger.Fatal("Error checking for test files")
			}

			if debugFlag {
				logger.Println("No Go Test files in DIR:", rel, "skipping")
			}

			return nil
		}

		wg.Add(1)

		if isLimited {
			semaphore <- struct{}{}
		}

		go processDIR(logger, wg, path, rel, out, semaphore)

		return nil
	}

	if err := filepath.Walk(projectPath, walker); err != nil {
		logger.Fatalf("\n**could not walk project path '%s'\n%s\n", projectPath, err)
	}

	go func() {
		wg.Wait()
		close(out)

		if isLimited {
			close(semaphore)
		}
	}()

	buff := bytes.NewBufferString("")

	for cover := range out {
		buff.Write(cover)
	}

	final := buff.String()
	final = modeRegex.ReplaceAllString(final, "")
	final = "mode: " + coverFlag + "\n" + final

	if err := ioutil.WriteFile(outFilename, []byte(final), 0644); err != nil {
		logger.Fatal("ERROR Writing \""+outFilename+"\"", err)
	}
}
Ejemplo n.º 10
0
// Dial a packet node using a Kenwood (or similar) radio over serial
func DialKenwood(dev, mycall, targetcall string, config Config, logger *log.Logger) (*KenwoodConn, error) {
	if logger == nil {
		logger = log.New(os.Stderr, "", log.LstdFlags)
	}

	localAddr, remoteAddr := tncAddrFromString(mycall), tncAddrFromString(targetcall)
	conn := &KenwoodConn{Conn{
		localAddr:  AX25Addr{localAddr},
		remoteAddr: AX25Addr{remoteAddr},
	}}

	if dev == "socket" {
		c, err := net.Dial("tcp", "127.0.0.1:8081")
		if err != nil {
			panic(err)
		}
		conn.Conn.ReadWriteCloser = c
	} else {
		c := &serial.Config{Name: dev, Baud: int(B9600)}
		s, err := serial.OpenPort(c)
		if err != nil {
			return conn, err
		} else {
			conn.Conn.ReadWriteCloser = s
		}
	}

	conn.Write([]byte{3, 3, 3}) // ETX
	fmt.Fprint(conn, "\r\nrestart\r\n")
	for {
		line, _ := wl2k.ReadLine(conn)

		if strings.HasPrefix(line, "cmd:") {
			fmt.Fprint(conn, "ECHO OFF\r") // Don't echo commands
			fmt.Fprint(conn, "FLOW OFF\r")
			fmt.Fprint(conn, "XFLOW ON\r")    // Enable software flow control
			fmt.Fprint(conn, "LFIGNORE ON\r") // Ignore linefeed (\n)
			fmt.Fprint(conn, "AUTOLF OFF\r")  // Don't auto-insert linefeed
			fmt.Fprint(conn, "CR ON\r")
			fmt.Fprint(conn, "8BITCONV ON\r") // Use 8-bit characters

			// Return to command mode if station of current I/O stream disconnects.
			fmt.Fprint(conn, "NEWMODE ON\r")

			time.Sleep(500 * time.Millisecond)

			fmt.Fprintf(conn, "MYCALL %s\r", mycall)
			fmt.Fprintf(conn, "HBAUD %d\r", config.HBaud)
			fmt.Fprintf(conn, "PACLEN %d\r", config.PacketLength)
			fmt.Fprintf(conn, "TXDELAY %d\r", config.TXDelay/_CONFIG_TXDELAY_UNIT)
			fmt.Fprintf(conn, "PERSIST %d\r", config.Persist)
			time.Sleep(500 * time.Millisecond)

			fmt.Fprintf(conn, "SLOTTIME %d\r", config.SlotTime/_CONFIG_SLOT_TIME_UNIT)
			fmt.Fprint(conn, "FULLDUP OFF\r")
			fmt.Fprintf(conn, "MAXFRAME %d\r", config.MaxFrame)
			fmt.Fprintf(conn, "FRACK %d\r", config.FRACK/_CONFIG_FRACK_UNIT)
			fmt.Fprintf(conn, "RESPTIME %d\r", config.ResponseTime/_CONFIG_RESPONSE_TIME_UNIT)
			fmt.Fprintf(conn, "NOMODE ON\r")

			break
		}
	}
	time.Sleep(2 * time.Second)

	fmt.Fprintf(conn, "\rc %s\r", targetcall)
	for {
		line, _ := wl2k.ReadLine(conn)
		logger.Println(line)
		line = strings.TrimSpace(line)

		if strings.Contains(line, "*** CONNECTED to") {
			fmt.Fprint(conn, "TRANS\r\n")
			return conn, nil
		} else if strings.Contains(line, "*** DISCONNECTED") {
			logger.Fatal("got disconnect ", int(line[len(line)-1]))
		}
	}

	return conn, nil
}
Ejemplo n.º 11
0
func main() {
	useSyslog := flag.Bool("syslog", false, "use syslog")

	flag.Parse()

	var logger *log.Logger
	if *useSyslog {
		var err error
		logger, err = syslog.NewLogger(syslog.LOG_INFO|syslog.LOG_DAEMON, 0)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Could not setup syslog logger: %v\n", err)
			os.Exit(1)
		}
	} else {
		logger = log.New(os.Stderr, "monsti ", log.LstdFlags)
	}

	// Load configuration
	if flag.NArg() != 1 {
		logger.Fatalf("Usage: %v <config_directory>\n",
			filepath.Base(os.Args[0]))
	}
	cfgPath := msettings.GetConfigPath(flag.Arg(0))
	var settings settings
	if err := msettings.LoadModuleSettings("daemon", cfgPath, &settings); err != nil {
		logger.Fatal("Could not load settings: ", err)
	}

	gettext.DefaultLocales.Domain = "monsti-daemon"
	gettext.DefaultLocales.LocaleDir = settings.Monsti.Directories.Locale

	var waitGroup sync.WaitGroup

	// Start service handler
	monstiPath := settings.Monsti.GetServicePath(service.MonstiService.String())
	monsti := new(MonstiService)
	monsti.Settings = &settings
	monsti.Logger = logger
	provider := service.NewProvider("Monsti", monsti)
	provider.Logger = logger
	if err := provider.Listen(monstiPath); err != nil {
		logger.Fatalf("service: Could not start service: %v", err)
	}
	waitGroup.Add(1)
	go func() {
		defer waitGroup.Done()
		if err := provider.Accept(); err != nil {
			logger.Fatalf("Could not accept at service: %v", err)
		}
	}()

	sessions := service.NewSessionPool(1, monstiPath)
	renderer := template.Renderer{Root: settings.Monsti.GetTemplatesPath()}

	// Init core functionality
	session, err := sessions.New()
	if err != nil {
		logger.Fatalf("Could not get session: %v", err)
	}
	if err := initNodeTypes(&settings, session, logger); err != nil {
		logger.Fatalf("Could not init node types: %v", err)
	}
	if err := initBlog(&settings, session, sessions, logger,
		&renderer); err != nil {
		logger.Fatalf("Could not init blog: %v", err)
	}

	// Wait for signals
	go func() {
		for {
			if err := session.Monsti().WaitSignal(); err != nil {
				logger.Fatalf("Could not wait for signal: %v", err)
			}
		}
	}()

	// Start modules
	monsti.moduleInit = make(map[string]chan bool)
	for _, module := range settings.Modules {
		monsti.moduleInit[module] = make(chan bool, 1)
	}
	for _, module := range settings.Modules {
		executable := "monsti-" + module
		cmd := exec.Command(executable, cfgPath)
		cmd.Stderr = moduleLog{module, logger}
		go func(module string) {
			if err := cmd.Run(); err != nil {
				logger.Fatalf("Module %q failed: %v", module, err)
			}
		}(module)
	}
	logger.Println("Waiting for modules to finish initialization...")
	for _, module := range settings.Modules {
		logger.Printf("Waiting for %q...", module)
		<-monsti.moduleInit[module]
	}

	// Setup up httpd
	handler := nodeHandler{
		Renderer: renderer,
		Settings: &settings,
		Log:      logger,
		Sessions: sessions,
	}
	monsti.Handler = &handler
	monsti.siteMutexes = make(map[string]*sync.RWMutex)

	http.Handle("/static/", http.FileServer(http.Dir(
		filepath.Dir(settings.Monsti.GetStaticsPath()))))
	handler.InitializedSites = make(map[string]bool)
	http.Handle("/", &handler)
	waitGroup.Add(1)
	go func() {
		if err := http.ListenAndServe(settings.Listen, nil); err != nil {
			logger.Fatal("HTTP Listener failed: ", err)
		}
		waitGroup.Done()
	}()

	logger.Printf("Monsti is up and running, listening on %q.", settings.Listen)
	waitGroup.Wait()
	logger.Println("Monsti is shutting down.")
}
Ejemplo n.º 12
0
Archivo: main.go Proyecto: ae6rt/decap
	},
}

var putS3Cmd = &cobra.Command{
	Use:   "s3put",
	Short: "put a file to an S3 bucket",
	Long:  `put a file to an S3 bucket`,
	Run: func(cmd *cobra.Command, args []string) {
		config := awsConfig()
		if debug {
			Log.Printf("%+v\n", config)
		}
		svc := s3.New(config)
		data, err := ioutil.ReadFile(fileName)
		if err != nil {
			Log.Fatal(err)
		}
		params := &s3.PutObjectInput{
			Bucket:        aws.String(bucketName),
			Key:           aws.String(buildID),
			Body:          bytes.NewReader(data),
			ContentType:   aws.String(contentType),
			ContentLength: aws.Int64(int64(len(data))),
		}
		if debug {
			Log.Printf("%+v\n", params)
		}
		if resp, err := svc.PutObject(params); err != nil {
			Log.Printf("%+v\n", resp)
			Log.Fatal(err.Error())
		} else {
Ejemplo n.º 13
0
func InitSlave(
	slaveEvents com.SlaveEvent,
	masterEvents com.MasterEvent,
	elevatorEvents com.ElevatorEvent,
	slaveLogger log.Logger) {

	slaveLogger.Print("Waiting for master")
	sendTicker := time.NewTicker(sendInterval)

	orders := make([]order.Order, 0)

	for {
		select {
		case message := <-slaveEvents.FromMaster:
			if len(orders) == 0 {
				slaveLogger.Printf("Initiating slave, master %s", message.Address)
				remainingOrders := slaveLoop(slaveEvents, masterEvents, elevatorEvents, slaveLogger)

				slaveLogger.Print("Waiting for new master")
				for _, order := range remainingOrders {
					if order.TakenBy == myIP {
						orders = append(orders, order)
					}
				}
			}

		case <-slaveEvents.MissedDeadline:
			driver.SetMotorDirection(driver.DirnStop)
			slaveLogger.Fatal("Failed to complete order within deadline")

		case floor := <-slaveEvents.CompletedFloor:
			slaveLogger.Printf("Completed floor %d", floor+1)
			for i := 0; i < len(orders); i++ {
				order := orders[i]
				if order.TakenBy == myIP && order.Button.Floor == floor {
					orders = append(orders[:i], orders[i+1:]...)
				}
			}
			elevData := elevator.GetElevData()
			order.PrioritizeOrders(orders, myIP, elevData.LastPassedFloor, elevData.CurrentDirection)
			driver.ClearAllButtonLamps()
			for _, o := range orders {
				if o.Button.Type == driver.ButtonCallCommand && o.TakenBy != myIP {
					continue
				}
				driver.SetButtonLamp(o.Button.Type, o.Button.Floor, 1)
			}
			priority := order.GetPriority(orders, myIP)
			if priority != nil {
				elevatorEvents.NewTargetFloor <- priority.Button.Floor
			}

		case button := <-slaveEvents.ButtonPressed:
			if button.Type == driver.ButtonCallCommand {
				orders = append(orders, order.Order{Button: button, TakenBy: myIP})
				elevData := elevator.GetElevData()
				order.PrioritizeOrders(orders, myIP, elevData.LastPassedFloor, elevData.CurrentDirection)
				driver.ClearAllButtonLamps()
				for _, o := range orders {
					if o.Button.Type == driver.ButtonCallCommand && o.TakenBy != myIP {
						continue
					}
					driver.SetButtonLamp(o.Button.Type, o.Button.Floor, 1)
				}
				priority := order.GetPriority(orders, myIP)
				if priority != nil {
					elevatorEvents.NewTargetFloor <- priority.Button.Floor
				}
			}

		case <-sendTicker.C:
			data := com.SlaveData{
				ElevData: elevator.GetElevData(),
			}
			slaveEvents.ToMaster <- network.UDPMessage{
				Data: com.EncodeSlaveData(data),
			}
			elevData := elevator.GetElevData()
			order.PrioritizeOrders(orders, myIP, elevData.LastPassedFloor, elevData.CurrentDirection)
			driver.ClearAllButtonLamps()
			for _, o := range orders {
				if o.Button.Type == driver.ButtonCallCommand && o.TakenBy != myIP {
					continue
				}
				driver.SetButtonLamp(o.Button.Type, o.Button.Floor, 1)
			}
			priority := order.GetPriority(orders, myIP)
			if priority != nil {
				elevatorEvents.NewTargetFloor <- priority.Button.Floor
			}
		}
	}
}