Пример #1
0
func openService(ns string, serviceName string, c *k8sclient.Client, printURL bool, retry bool) {
	if retry {
		if err := RetryAfter(40, func() error { return CheckService(ns, serviceName, c) }, 10*time.Second); err != nil {
			util.Errorf("Could not find finalized endpoint being pointed to by %s: %v", serviceName, err)
			os.Exit(1)
		}
	}
	svcs, err := c.Services(ns).List(kubeApi.ListOptions{})
	if err != nil {
		util.Errorf("No services found %v\n", err)
	}
	found := false
	for _, service := range svcs.Items {
		if serviceName == service.Name {

			url := service.ObjectMeta.Annotations[exposeURLAnnotation]

			if printURL {
				util.Successf("%s\n", url)
			} else {
				util.Successf("\nOpening URL %s\n", url)
				browser.OpenURL(url)
			}
			found = true
			break
		}
	}
	if !found {
		util.Errorf("No service %s in namespace %s\n", serviceName, ns)
	}
}
Пример #2
0
func StackoverflowceptionCheck(err error) bool {
	if err != nil {
		url := "http://stackoverflow.com/search?q="
		url += err.Error()
		browser.OpenURL(url)
		return true
	}
	return false
}
Пример #3
0
// Opens a browser tab/window with the login to pocket for authorization.
// Only returns when the user presses enter.
func authorizeInBrowser(requestToken string, redirectURI string) {
	template := "https://getpocket.com/auth/authorize?" +
		"request_token=%s&redirect_uri=%s"
	url := fmt.Sprintf(template, requestToken, redirectURI)
	browser.OpenURL(url)

	reader := bufio.NewReader(os.Stdin)
	fmt.Println("Press enter when authorized")
	_, err := reader.ReadString('\n')
	checkFatal(err)
}
Пример #4
0
func main() {

	var err error

	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "Usage of %s: command <args>...\n", os.Args[0])
		flag.PrintDefaults()
	}

	flag.Parse()
	if len(flag.Args()) < 1 {
		flag.Usage()
		return
	}

	ifaceAndPort := fmt.Sprintf("%v:0", *iface)
	listener, err := net.Listen("tcp4", ifaceAndPort)
	if err != nil {
		log.Fatal(err)
	}

	pr, pw, _ := os.Pipe()
	gcChan := make(chan *gctrace, 1)
	scvgChan := make(chan *scvgtrace, 1)

	parser := Parser{
		reader:   pr,
		gcChan:   gcChan,
		scvgChan: scvgChan,
	}

	gcvisGraph = NewGraph(strings.Join(flag.Args(), " "), GCVIS_TMPL)

	go startSubprocess(pw, flag.Args())
	go parser.Run()

	http.HandleFunc("/", indexHandler)

	go http.Serve(listener, nil)

	url := fmt.Sprintf("http://%s/", listener.Addr())
	log.Printf("opening browser window, if this fails, navigate to %s", url)
	browser.OpenURL(url)

	for {
		select {
		case gcTrace := <-gcChan:
			gcvisGraph.AddGCTraceGraphPoint(gcTrace)
		case scvgTrace := <-scvgChan:
			gcvisGraph.AddScavengerGraphPoint(scvgTrace)
		}
	}
}
Пример #5
0
// main is the entry point for the application.
func main() {
	print("Starting - HTTP service on port 8676\n")
	print("Press 'ctrl + c' to quit\n")
	folderPath, err := osext.ExecutableFolder()
	if err != nil {
		print(err)
	}

	browser.OpenURL("http://localhost:8676/index.html")

	panic(http.ListenAndServe(":8676", http.FileServer(http.Dir(folderPath))))

}
Пример #6
0
func main() {
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "Usage of %s: command <args>...\n", os.Args[0])
		flag.PrintDefaults()
	}

	flag.Parse()
	if len(flag.Args()) < 1 {
		flag.Usage()
		return
	}

	subcommand := NewSubCommand(flag.Args())
	parser := NewParser(subcommand.PipeRead)
	gcvisGraph := NewGraph(strings.Join(flag.Args(), " "), GCVIS_TMPL)
	server := NewHttpServer(*iface, *port, &gcvisGraph)

	go subcommand.Run()
	go parser.Run()
	go server.Start()

	url := server.Url()
	log.Printf("opening browser window, if this fails, navigate to %s", url)
	browser.OpenURL(url)

	for {
		select {
		case gcTrace := <-parser.GcChan:
			gcvisGraph.AddGCTraceGraphPoint(gcTrace)
		case scvgTrace := <-parser.ScvgChan:
			gcvisGraph.AddScavengerGraphPoint(scvgTrace)
		case output := <-parser.NoMatchChan:
			fmt.Fprintln(os.Stderr, output)
		case <-parser.done:
			if parser.Err != nil {
				fmt.Fprintf(os.Stderr, parser.Err.Error())
				os.Exit(1)
			}

			if subcommand.Err() != nil {
				fmt.Fprintf(os.Stderr, subcommand.Err().Error())
				os.Exit(1)
			}

			os.Exit(0)
		}
	}
}
Пример #7
0
func ListenAndServe(stateFile, addr, central string, devMode bool) error {
	server, err := New(stateFile, central)
	if err != nil {
		return err
	}
	if !devMode {
		host := addr
		if strings.HasPrefix(host, ":") {
			host = "localhost" + host
		}
		err := browser.OpenURL("http://" + host + "/")
		if err != nil {
			log.Println(err)
		}
	}
	return server.ListenAndServe(addr, devMode)
}
Пример #8
0
// Open opens a product on the amazon website
func Open(c *cli.Context) {
	api := api.Create(c.GlobalString("locale"))

	conf := config.GetConfig()
	asin, exists := conf.ASINFromCache("Products", c.Args().First())
	if !exists {
		fmt.Fprintln(os.Stderr, "Cannot look up ASIN")
		os.Exit(1)
	}

	result, err := api.ItemLookup(asin, "Small")

	if err != nil {
		panic(err)
	}

	browser.OpenURL(result.Items.ItemList[0].DetailPageURL)
}
Пример #9
0
Файл: server.go Проект: kego/ke
func serve(ctx context.Context) error {

	wgctx.Add(ctx, "serve")
	defer wgctx.Done(ctx, "serve")

	env := envctx.FromContext(ctx)
	cmd := cmdctx.FromContext(ctx)

	// Starting with port zero chooses a random open port
	listner, err := net.Listen("tcp", fmt.Sprintf(":%d", cmd.Port))
	if err != nil {
		return kerr.Wrap("QGLXHWPWQW", err)
	}
	defer listner.Close()

	// Here we get the address we're serving on
	address, ok := listner.Addr().(*net.TCPAddr)
	if !ok {
		return kerr.New("CBLPYVGGUR", "Can't find address (l.Addr() is not *net.TCPAddr)")
	}

	url := fmt.Sprintf("http://localhost:%d/%s/", address.Port, env.Path)

	cmd.Printf("Server now running on %s\n", url)

	// We open the default browser and navigate to the address we're serving
	// from. This will error if the system doesn't have a browser, so we can
	// ignore the error.
	browser.OpenURL(url)

	withCancel(ctx, func() {
		err = http.Serve(listner, nil)
	})
	if err != nil {
		return kerr.Wrap("TUCBTWMRNN", err)
	}

	if cmd.Debug {
		return kerr.New("ATUTBOICGJ", "Connection closed")
	}
	return nil

}
Пример #10
0
// Checkout initiates the checkout for a cart
func Checkout(c *cli.Context) {
	api := api.Create(c.GlobalString("locale"))

	conf := config.GetConfig()
	defer conf.Flush()

	cartName := conf.CartNameFromCache(c.Args().First())

	if cart, exists := conf.Carts[cartName]; exists {
		if getResponse, getErr := api.CartGet(cart.CartID, cart.HMAC); getErr == nil {
			delete(conf.Carts, cartName)
			browser.OpenURL(getResponse.Cart.PurchaseURL)
		} else {
			panic(getErr)
		}
	} else {
		fmt.Fprintf(os.Stderr, "Cart %s is unknown\n", cartName)
		os.Exit(1)
	}
}
Пример #11
0
func main() {
	if len(os.Args) < 2 {
		log.Fatalf("usage: %s command <args>...", os.Args[0])
	}
	pr, pw, _ := os.Pipe()
	gc := make(chan *gctrace, 1)
	scvg := make(chan *scvgtrace, 1)

	go startSubprocess(pw)
	go startParser(pr, gc, scvg)

	l, err := net.Listen("tcp4", "127.0.0.1:0")
	if err != nil {
		log.Fatal(err)
	}
	http.HandleFunc("/", index)
	go http.Serve(l, nil)

	url := fmt.Sprintf("http://%s/", l.Addr())
	log.Printf("opening browser window, if this fails, navigate to %s", url)
	browser.OpenURL(url)

	for {
		select {
		case gc := <-gc:
			mu.Lock()
			ts := int(time.Now().UnixNano() / 1e6)
			heapuse = append(heapuse, graphPoints{ts, gc.Heap1})
			mu.Unlock()
		case scvg := <-scvg:
			mu.Lock()
			ts := int(time.Now().UnixNano() / 1e6)
			scvginuse = append(scvginuse, graphPoints{ts, scvg.inuse})
			scvgidle = append(scvgidle, graphPoints{ts, scvg.idle})
			scvgsys = append(scvgsys, graphPoints{ts, scvg.sys})
			scvgreleased = append(scvgreleased, graphPoints{ts, scvg.released})
			scvgconsumed = append(scvgconsumed, graphPoints{ts, scvg.consumed})
			mu.Unlock()
		}
	}
}
Пример #12
0
func openURL(data string, isHTML bool) error {
	if isHTML {
		tmpfile, err := ioutil.TempFile("", "pmbopenurl")
		if err != nil {
			return err
		}

		_, err = tmpfile.Write([]byte(data))
		if err != nil {
			return err
		}

		err = tmpfile.Close()
		if err != nil {
			return err
		}

		nameWithSuffix := fmt.Sprintf("%s.html", tmpfile.Name())
		err = os.Rename(tmpfile.Name(), nameWithSuffix)
		if err != nil {
			return err
		}

		go func() {
			time.Sleep(15 * time.Second)
			logrus.Infof("cleaning up temporary file: %s", nameWithSuffix)
			os.Remove(nameWithSuffix)
		}()

		logrus.Infof("opening file: %s", nameWithSuffix)
		return browser.OpenFile(nameWithSuffix)
	}

	logrus.Infof("opening url: %s", data)
	return browser.OpenURL(data)
}
Пример #13
0
func doServe(c *cli.Context) {
	master := c.Bool("master")
	theme := c.String("theme")

	// Get the presentation path from the command line, or grab the current directory.
	presentationPath, _ := os.Getwd()
	if len(c.Args()) > 0 {
		presentationPath = c.Args()[0]
	}

	// Check if the path is relative.
	if !strings.HasPrefix(presentationPath, "/") {
		presentationPath, _ = filepath.Abs(presentationPath)
	}

	// Check if there is a presentation file present.
	if _, err := os.Stat(path.Join(presentationPath, "slides.md")); err != nil {
		fmt.Printf("slides.md does not exist at %s\n", presentationPath)
		os.Exit(1)
	}

	if theme != "" {
		fmt.Println("Using one of the packaged themes ...")
		http.Handle("/css/", http.FileServer(&assetfs.AssetFS{Asset, AssetDir, "themes/" + theme}))
		http.Handle("/fonts/", http.FileServer(&assetfs.AssetFS{Asset, AssetDir, "themes/" + theme}))
	} else {
		if _, err := os.Stat(path.Join(presentationPath, "css", "theme.css")); err == nil {
			fmt.Println("Found a theme, using it ...")
			http.Handle("/css/", http.FileServer(http.Dir(presentationPath)))
			http.Handle("/fonts/", http.FileServer(http.Dir(presentationPath)))
		} else {
			fmt.Println("No theme found ...")
		}
	}

	// Handle the slides.
	http.HandleFunc("/slides.md", func(w http.ResponseWriter, r *http.Request) {
		t, _ := template.ParseFiles(path.Join(presentationPath, "slides.md"))
		t.Execute(w, "")
	})

	// Handle images.
	http.HandleFunc("/img/", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, path.Join(presentationPath, r.URL.Path))
	})

	// Handle reveal.js files.
	http.Handle("/reveal.js/css/", http.FileServer(&assetfs.AssetFS{Asset, AssetDir, ""}))
	http.Handle("/reveal.js/js/", http.FileServer(&assetfs.AssetFS{Asset, AssetDir, ""}))
	http.Handle("/reveal.js/lib/", http.FileServer(&assetfs.AssetFS{Asset, AssetDir, ""}))
	http.Handle("/reveal.js/plugin/", http.FileServer(&assetfs.AssetFS{Asset, AssetDir, ""}))

	// Handle the website.
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		opt := &Option{Markdown: "slides.md", Master: master}
		indexHTML, _ := Asset("assets/index.html")
		indexTemplate := template.Must(template.New("index").Parse(string(indexHTML)))
		indexTemplate.Execute(w, opt)
	})

	fmt.Println("Opening browser and redirecting to the presentation ...")
	browser.OpenURL("http://localhost:8989")

	err := http.ListenAndServe(":8989", nil)
	panic("Error while serving slides: " + err.Error())
}
Пример #14
0
		defer api.Close()

		url, err := cluster.GetServiceURL(api, namespace, service, serviceURLTemplate)
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			if _, ok := err.(cluster.MissingNodePortError); !ok {
				fmt.Fprintln(os.Stderr, "Check that minishift is running and that you have specified the correct namespace (-n flag).")
			}
			os.Exit(1)
		}

		if https {
			url = strings.Replace(url, "http", "https", 1)
		}
		if serviceURLMode {
			fmt.Fprintln(os.Stdout, url)
		} else {
			fmt.Fprintln(os.Stdout, "Opening kubernetes service "+namespace+"/"+service+" in default browser...")
			browser.OpenURL(url)
		}
	},
}

func init() {
	serviceCmd.Flags().StringVarP(&namespace, "namespace", "n", "default", "The service namespace")
	serviceCmd.Flags().BoolVar(&serviceURLMode, "url", false, "Display the kubernetes service URL in the CLI instead of opening it in the default browser")
	serviceCmd.PersistentFlags().StringVar(&serviceURLFormat, "format", "http://{{.IP}}:{{.Port}}", "Format to output service URL in")
	serviceCmd.Flags().BoolVar(&https, "https", false, "Open the service URL with https instead of http")
	RootCmd.AddCommand(serviceCmd)
}
Пример #15
0
func main() {
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "Usage of %s: command <args>...\n", os.Args[0])
		flag.PrintDefaults()
	}

	var pipeRead io.ReadCloser
	var subcommand *SubCommand

	flag.Parse()
	if len(flag.Args()) < 1 {
		if terminal.IsTerminal(int(os.Stdin.Fd())) {
			flag.Usage()
			return
		} else {
			pipeRead = os.Stdin
		}
	} else {
		subcommand = NewSubCommand(flag.Args())
		pipeRead = subcommand.PipeRead
		go subcommand.Run()
	}

	parser := NewParser(pipeRead)
	gcvisGraph := NewGraph(strings.Join(flag.Args(), " "), GCVIS_TMPL)
	server := NewHttpServer(*iface, *port, &gcvisGraph)

	go parser.Run()
	go server.Start()

	url := server.Url()

	if *openBrowser {
		log.Printf("opening browser window, if this fails, navigate to %s", url)
		browser.OpenURL(url)
	} else {
		log.Printf("server started on %s", url)
	}

	for {
		select {
		case gcTrace := <-parser.GcChan:
			gcvisGraph.AddGCTraceGraphPoint(gcTrace)
		case scvgTrace := <-parser.ScvgChan:
			gcvisGraph.AddScavengerGraphPoint(scvgTrace)
		case output := <-parser.NoMatchChan:
			fmt.Fprintln(os.Stderr, output)
		case <-parser.done:
			if parser.Err != nil {
				fmt.Fprintf(os.Stderr, parser.Err.Error())
				os.Exit(1)
			}

			break
		}
	}

	if subcommand != nil && subcommand.Err() != nil {
		fmt.Fprintf(os.Stderr, subcommand.Err().Error())
		os.Exit(1)
	}

	os.Exit(0)
}
Пример #16
0
func handleEvents(eventChan chan termbox.Event) {
	for ev := range eventChan {
		switch ev.Type {
		case termbox.EventKey:
			switch ev.Key {
			case termbox.KeyArrowUp:

			case termbox.KeyArrowDown:

			case termbox.KeySpace:
				// page down
				lock.Lock()
				totalN := len(events)
				lock.Unlock()
				if selectedRow >= totalN-1 {
					// the last event
					continue
				}

				if !detailView {
					if selectedRow/pageSize == totalN/pageSize {
						// already the last page, do nothing
						continue
					}

					selectedRow += pageSize
					if selectedRow > totalN-1 {
						// can't be beyond the range
						selectedRow = totalN - 1
					}
					page++

					redrawAll()
				}
				continue

			case termbox.KeyEnter:
				if detailView {
					browser.OpenURL(currentWebHook.Commits[len(currentWebHook.Commits)-selectedCommit-1].Url)
				}
				continue

			case termbox.KeyCtrlD:
				// dashboard page
				if dashboardView {
					redrawAll()
				} else {
					drawDashboardByHour()
				}
				dashboardView = !dashboardView

			case termbox.KeyCtrlP:
				if projectSummaryView {
					redrawAll()
				} else {
					drawDashboardByProject()
				}
				projectSummaryView = !projectSummaryView

			case termbox.KeyCtrlU:
				if userSummaryView {
					redrawAll()
				} else {
					drawDashboardByUser()
				}
				userSummaryView = !userSummaryView

			case termbox.KeyEsc:
				if detailView {
					detailView = false
					redrawAll()
				} else {
					termbox.Close()
					os.Exit(0)
				}
			}

			switch ev.Ch {
			case 'j':
				if detailView {
					if selectedCommit < len(currentWebHook.Commits)-1 {
						selectedCommit++
					} else {
						selectedCommit = 0 // rewind
					}
					drawDetail()
				} else {
					lock.Lock()
					totalN := len(events)
					lock.Unlock()

					if selectedRow < totalN-1 {
						selectedRow++
						if selectedRow%pageSize == 0 {
							page++
						}
						redrawAll()
					}
				}

			case 'K', 'T':
				if mainView {
					page = 0
					selectedRow = 0
					redrawAll()
				}

			case 'G':
				if mainView {
					lock.Lock()
					totalN := len(events)
					lock.Unlock()

					page = totalN / pageSize
					if totalN%pageSize == 0 {
						page--
					}

					selectedRow = totalN - 1
					redrawAll()
				}

			case 'M':
				if !detailView {
					lock.Lock()
					totalN := len(events)
					lock.Unlock()

					if selectedRow/pageSize == totalN/pageSize {
						// already the last page, do nothing
						continue
					}

					selectedRow = page*pageSize + pageSize/2
					redrawAll()
				}

			case 'H':
				if !detailView {
					selectedRow = page * pageSize
					redrawAll()
				}

			case 'L':
				if !detailView {
					lock.Lock()
					totalN := len(events)
					lock.Unlock()

					if selectedRow/pageSize == totalN/pageSize {
						// already the last page, do nothing
						continue
					}

					selectedRow = page*pageSize + pageSize - 1
					redrawAll()
				}

			case 'k':
				if detailView {
					if selectedCommit > 0 {
						selectedCommit--
					} else {
						selectedCommit = len(currentWebHook.Commits) - 1
					}
					drawDetail()
				} else {
					if selectedRow > 0 {
						if selectedRow%pageSize == 0 {
							page--
						}
						selectedRow--
						redrawAll()
					}
				}

			case 'd':
				// detail page
				if detailView {
					redrawAll()
				} else {
					drawDetail()
				}
				detailView = !detailView

			case 'b':
				// page up
				if !detailView {
					selectedRow -= pageSize
					if selectedRow < 0 {
						selectedRow = 0
					} else {
						page--
					}
					redrawAll()
				}

			case 'q':
				if detailView {
					detailView = false
					redrawAll()
				} else if dashboardView {
					dashboardView = false
					redrawAll()
				} else if projectSummaryView {
					projectSummaryView = false
					redrawAll()
				} else if userSummaryView {
					userSummaryView = false
					redrawAll()
				} else {
					termbox.Close()
					os.Exit(0)
				}
				selectedCommit = 0
			}

		case termbox.EventError:
			panic(ev.Err)

		}
	}
}
Пример #17
0
func main() {
	//Create channels
	symbols := make(chan string)
	output := make(chan string)

	//Stage some workers
	for w := 1; w <= 10; w++ {
		wg.Add(1)
		go worker(symbols, output)
	}

	//Get symbol list from file
	f, _ := os.Open("C:\\temp\\test\\symbols.txt")
	defer f.Close()

	//Read file lines into slice
	scanner := bufio.NewScanner(f)
	scanner.Split(bufio.ScanLines)

	var symlist []string

	for scanner.Scan() {
		symlist = append(symlist, scanner.Text())
	}

	//Process each symbol
	go func() {
		for _, v := range symlist {
			symbols <- v
		}
		close(symbols)
	}()

	//Wait for workers to complete
	go func() {
		wg.Wait()
		close(output)
	}()

	//Spit out status as files complete
	for i := range output {
		fmt.Println(i)
	}

	fmt.Println("Done...")

	//...and now the for the web stuff...

	fns := template.FuncMap{
		"start": func(x int) bool {
			if (x+1)%3 == 1 {
				return true
			}
			return false
		},
		"finish": func(x, y int) bool {
			if (y+1) == x || (y+1)%3 == 0 {
				return true
			}
			return false
		},
	}

	//Parse template
	tmpl := template.Must(template.New("main").Funcs(fns).ParseGlob("*.gohtml"))

	//Function
	http.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir("c:\\temp\\test\\"))))
	http.HandleFunc("/", func(res http.ResponseWriter, req *http.Request) {
		// execute template
		tmpl.ExecuteTemplate(res, "tmpl.gohtml", symlist)
	})

	//Call it...
	go browser.OpenURL("http://localhost:9002")

	// create server
	http.ListenAndServe(":9002", nil)
}
Пример #18
0
func startInternalHTTPServer(authKey string) error {

	lg.V(15).Infoln("starting internal api server")
	mux, err := createServeMux()
	if err != nil {
		lg.Error("failed to create router")
		return err
	}

	auth := Auth{Key: authKey, wrapped: mux}
	conf := clientconfig.Get()
	listener, err := net.Listen("tcp", conf.Settings.Local.ClientBindAddr)
	if err != nil {
		lg.Warning(err)
		listener, err = net.Listen("tcp", "127.0.0.1:")
	}
	if err != nil {
		lg.Warning(err)
		ui.Notify("Could not bind any local port (bootstrap)")
		lg.Errorln("Could not bind any local port (bootstrap)")
		return err
	}

	go func(listenaddr string) {
		// baseURL := fmt.Sprintf()
		baseURL := fmt.Sprintf("http://%s?suk=", listenaddr)
		for {
			select {
			case <-ui.Actions.CopyBrowserCodeToClipboard:
				bc := browsercode.BrowserCode{Key: authKey}
				err := bc.SetHostport(listener.Addr().String())
				if err != nil {
					lg.Errorln(err)
					continue
				}
				err = bc.CopyToClipboard()
				if err != nil {
					lg.Errorln(err)
				}

			case <-ui.Actions.OpenInBrowser:
				browser.OpenURL(baseURL + singleUseKeys.New() + "#/")

			case <-ui.Actions.Help:
				browser.OpenURL(baseURL + singleUseKeys.New() + "#/docs/__/index")
			}
			singleUseKeys.Cleanup()
		}
	}(listener.Addr().String())

	doneC := make(chan bool, 1)
	go func() {
		defer listener.Close()
		err = http.Serve(listener, auth)
		if err != nil {
			doneC <- false
		}
	}()
	select {
	case ok := <-doneC:
		if !ok {
			return errors.New("Could not start internal http server")
		}
	case <-time.After(time.Millisecond * 200):
		return nil
	}
	return nil
}
Пример #19
0
// Serve the presentation.
func Serve(c *cli.Context) {
	master := c.Bool("master")
	theme := c.String("theme")

	// Get the presentation path from the command line, or grab the current directory.
	presentationPath, _ := os.Getwd()
	if len(c.Args()) > 0 {
		presentationPath = c.Args()[0]
	}

	// Check if the path is relative.
	if !pathIsAbsolute(presentationPath) {
		presentationPath, _ = filepath.Abs(presentationPath)
	}

	// Check if there is a presentation file present.
	if fileExists(path.Join(presentationPath, "slides.md")) {
		log.Printf("slides.md does not exist at %s\n", presentationPath)
		os.Exit(1)
	}

	// Check if a theme was passed.
	if themeExists(theme) {
		log.Printf("Using build-in theme [%s]\n", theme)
		http.Handle("/css/", http.FileServer(&assetfs.AssetFS{bindata.Asset, bindata.AssetDir, bindata.AssetInfo, "themes/" + theme}))
		http.Handle("/fonts/", http.FileServer(&assetfs.AssetFS{bindata.Asset, bindata.AssetDir, bindata.AssetInfo, "themes/" + theme}))
	} else {
		if !fileExists(path.Join(presentationPath, "css", "theme.css")) {
			log.Println("Found a theme in the css directory, using it...")
			http.Handle("/css/", http.FileServer(http.Dir(presentationPath)))
			http.Handle("/fonts/", http.FileServer(http.Dir(presentationPath)))
		} else {
			log.Println("No theme found ...")
		}
	}

	// Handle the slides.
	http.HandleFunc("/slides.md", func(w http.ResponseWriter, r *http.Request) {
		t, _ := template.ParseFiles(path.Join(presentationPath, "slides.md"))
		t.Execute(w, "")
	})

	// Handle images.
	http.HandleFunc("/img/", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, path.Join(presentationPath, r.URL.Path))
	})

	// Handle reveal.js files.
	http.Handle("/reveal.js/css/", http.FileServer(&assetfs.AssetFS{bindata.Asset, bindata.AssetDir, bindata.AssetInfo, ""}))
	http.Handle("/reveal.js/js/", http.FileServer(&assetfs.AssetFS{bindata.Asset, bindata.AssetDir, bindata.AssetInfo, ""}))
	http.Handle("/reveal.js/lib/", http.FileServer(&assetfs.AssetFS{bindata.Asset, bindata.AssetDir, bindata.AssetInfo, ""}))
	http.Handle("/reveal.js/plugin/", http.FileServer(&assetfs.AssetFS{bindata.Asset, bindata.AssetDir, bindata.AssetInfo, ""}))

	// Handle the website.
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		opt := &Option{Markdown: "slides.md", Master: master}
		indexHTML, _ := bindata.Asset("assets/index.html")
		indexTemplate := template.Must(template.New("index").Parse(string(indexHTML)))
		indexTemplate.Execute(w, opt)
	})

	log.Println("Serving presentation on http://localhost:8989")
	log.Println("Opening browser and redirecting to the presentation, press Ctrl-C to stop ...")
	browser.OpenURL("http://localhost:8989")

	err := http.ListenAndServe(":8989", nil)
	log.Fatalf("Error while serving slides: %s\n", err.Error())
}
Пример #20
0
func AuthorizePocket(code string, callbackUrl string) {
	browser.OpenURL("https://getpocket.com/auth/authorize?request_token=" + code + "&redirect_uri=" + callbackUrl)
}
Пример #21
0
// Monitor monitors log aggregates results into RunStats
func Monitor(bf int) RunStats {
	log.Println("MONITORING")
	defer fmt.Println("DONE MONITORING")
retry_dial:
	ws, err := websocket.Dial("ws://localhost:8080/log", "", "http://localhost/")
	if err != nil {
		time.Sleep(1 * time.Second)
		goto retry_dial
	}
retry:
	// Get HTML of webpage for data (NHosts, Depth, ...)
	doc, err := goquery.NewDocument("http://localhost:8080/")
	if err != nil {
		log.Println("unable to get log data: retrying:", err)
		time.Sleep(10 * time.Second)
		goto retry
	}
	if view {
		browser.OpenURL("http://localhost:8080/")
	}
	nhosts := doc.Find("#numhosts").First().Text()
	log.Println("hosts:", nhosts)
	depth := doc.Find("#depth").First().Text()
	log.Println("depth:", depth)
	nh, err := strconv.Atoi(nhosts)
	if err != nil {
		log.Fatal("unable to convert hosts to be a number:", nhosts)
	}
	d, err := strconv.Atoi(depth)
	if err != nil {
		log.Fatal("unable to convert depth to be a number:", depth)
	}
	clientDone := false
	rootDone := false
	var rs RunStats
	rs.NHosts = nh
	rs.Depth = d
	rs.BF = bf

	var M, S float64
	k := float64(1)
	first := true
	for {
		var data []byte
		err := websocket.Message.Receive(ws, &data)
		if err != nil {
			// if it is an eof error than stop reading
			if err == io.EOF {
				log.Println("websocket terminated before emitting EOF or terminating string")
				break
			}
			continue
		}
		if bytes.Contains(data, []byte("EOF")) || bytes.Contains(data, []byte("terminating")) {
			log.Printf(
				"EOF/terminating Detected: need forkexec to report and clients: rootDone(%t) clientDone(%t)",
				rootDone, clientDone)
		}
		if bytes.Contains(data, []byte("root_round")) {
			if clientDone || rootDone {
				// ignore after we have received our first EOF
				continue
			}
			var entry StatsEntry
			err := json.Unmarshal(data, &entry)
			if err != nil {
				log.Fatal("json unmarshalled improperly:", err)
			}
			log.Println("root_round:", entry)
			if first {
				first = false
				rs.MinTime = entry.Time
				rs.MaxTime = entry.Time
			}
			if entry.Time < rs.MinTime {
				rs.MinTime = entry.Time
			} else if entry.Time > rs.MaxTime {
				rs.MaxTime = entry.Time
			}

			rs.AvgTime = ((rs.AvgTime * (k - 1)) + entry.Time) / k

			var tM = M
			M += (entry.Time - tM) / k
			S += (entry.Time - tM) * (entry.Time - M)
			k++
			rs.StdDev = math.Sqrt(S / (k - 1))
		} else if bytes.Contains(data, []byte("forkexec")) {
			if rootDone {
				continue
			}
			var ss SysStats
			err := json.Unmarshal(data, &ss)
			if err != nil {
				log.Fatal("unable to unmarshal forkexec:", ss)
			}
			rs.SysTime = ss.SysTime
			rs.UserTime = ss.UserTime
			log.Println("FORKEXEC:", ss)
			if clientDone {
				break
			}
			rootDone = true
		} else if bytes.Contains(data, []byte("client_msg_stats")) {
			if clientDone {
				continue
			}
			var cms ClientMsgStats
			err := json.Unmarshal(data, &cms)
			if err != nil {
				log.Fatal("unable to unmarshal client_msg_stats:", string(data))
			}
			// what do I want to keep out of the Client Message States
			// cms.Buckets stores how many were processed at time T
			// cms.RoundsAfter stores how many rounds delayed it was
			//
			// get the average delay (roundsAfter), max and min
			// get the total number of messages timestamped
			// get the average number of messages timestamped per second?
			avg, _, _, _ := ArrStats(cms.Buckets)
			// get the observed rate of processed messages
			// avg is how many messages per second, we want how many milliseconds between messages
			observed := avg / 1000 // set avg to messages per milliseconds
			observed = 1 / observed
			rs.Rate = observed
			rs.Times = cms.Times
			if rootDone {
				break
			}
			clientDone = true
		}
	}
	return rs
}
Пример #22
0
func ServeHTTP() error {
	logger := log.New()
	installer := NewInstaller(logger)

	api := &httpAPI{
		Installer: installer,
		logger:    logger,
		clientConfig: installerJSConfig{
			Endpoints: map[string]string{
				"clusters":           "/clusters",
				"cluster":            "/clusters/:id",
				"upload_backup":      "/clusters/:id/upload-backup",
				"cert":               "/clusters/:id/ca-cert",
				"events":             "/events",
				"prompt":             "/clusters/:id/prompts/:prompt_id",
				"credentials":        "/credentials",
				"regions":            "/regions",
				"azureSubscriptions": "/azure/subscriptions",
			},
		},
	}

	if creds, err := aws.EnvCreds(); err == nil {
		api.AWSEnvCreds = creds
		if c, err := creds.Credentials(); err == nil {
			api.clientConfig.HasAWSEnvCredentials = true
			api.clientConfig.AWSEnvCredentialsID = c.AccessKeyID
		}
	}

	httpRouter := httprouter.New()

	httpRouter.GET("/", api.ServeTemplate)
	httpRouter.GET("/credentials", api.ServeTemplate)
	httpRouter.GET("/credentials/:id", api.ServeTemplate)
	httpRouter.GET("/clusters/:id", api.ServeTemplate)
	httpRouter.POST("/clusters/:id/upload-backup", api.ReceiveBackup)
	httpRouter.GET("/clusters/:id/ca-cert", api.GetCert)
	httpRouter.GET("/clusters/:id/delete", api.ServeTemplate)
	httpRouter.GET("/oauth/azure", api.ServeTemplate)
	httpRouter.DELETE("/clusters/:id", api.DeleteCluster)
	httpRouter.GET("/clusters", api.RedirectRoot)
	httpRouter.POST("/clusters", api.LaunchCluster)
	httpRouter.GET("/events", api.Events)
	httpRouter.POST("/clusters/:id/prompts/:prompt_id", api.Prompt)
	httpRouter.GET("/assets/*assetPath", api.ServeAsset)
	httpRouter.POST("/credentials", api.NewCredential)
	httpRouter.DELETE("/credentials/:type/:id", api.DeleteCredential)
	httpRouter.GET("/regions", api.GetCloudRegions)
	httpRouter.GET("/azure/subscriptions", api.GetAzureSubscriptions)

	port := os.Getenv("PORT")
	if port == "" {
		// if no port is given, use a random one
		port = "0"
	}

	l, err := net.Listen("tcp", fmt.Sprintf(":%s", port))
	if err != nil {
		return err
	}
	addr := fmt.Sprintf("http://localhost:%d", l.Addr().(*net.TCPAddr).Port)
	fmt.Printf("Open %s in your browser to continue.\n", addr)
	browser.OpenURL(addr)
	return http.Serve(l, api.CorsHandler(httpRouter, addr))
}
Пример #23
0
func main() {
	flag.BoolVar(&debug, "debug", false, "print debug info")
	web := flag.Bool("web", false, "show result in browser and start a web server")
	open := flag.Bool("open", false, "open browser")
	query := flag.String("q", "", "godoc query keyword")
	port := flag.String("port", "9090", "web server port number")
	flag.StringVar(&token, "github-token", "", "github token for more github requests")
	flag.Parse()

	if token == "" {
		fmt.Println("specify -github-token can increase github api rate limits: https://github.com/settings/tokens")
	}

	if *web {
		type data struct {
			Query               string
			GitHubs, NonGitHubs []*Critique
		}
		caches := map[string]data{}
		http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
			query := strings.TrimSpace(r.URL.Query().Get("query"))
			if query != "" {
				log.Println("Query:", query)
			}
			d, ok := caches[query]
			if ok {
				goto render
			} else if query != "" {
				githubs, nonGithubs, err := report(query)
				if err != nil {
					log.Println(err)
					if _, err := w.Write([]byte(err.Error() + "\n" + string(debugpkg.Stack()))); err != nil {
						log.Println(err)
					}
					debugpkg.PrintStack()
					return
				}
				d = data{
					Query:      query,
					GitHubs:    githubs,
					NonGitHubs: nonGithubs,
				}
				caches[query] = d
			}

		render:
			if err := tmpl.ExecuteTemplate(w, "main", d); err != nil {
				log.Println(err)
			}
		})

		log.Println("Listening on :" + *port)
		if *open {
			if err := browser.OpenURL("http://localhost:" + *port); err != nil {
				log.Println(err)
			}
		}
		log.Fatal(http.ListenAndServe(":"+*port, nil))
	} else {
		if *query == "" {
			log.Println("Please specify query keyword by -q")
			os.Exit(1)
		}
		githubs, nonGithubs, err := report(*query)
		if err != nil {
			exit(err)
		}

		for i, pkgs := range [][]*Critique{githubs, nonGithubs} {
			fmt.Println("===========================")
			if i == 0 {
				fmt.Println("GitHub Packages")
			} else {
				fmt.Println("Non-GitHub Packages")
			}
			printPkgs(pkgs, "")
		}
	}
}
Пример #24
-1
func main() {
	params := struct {
		User string `flag:"user,ssh connection username"`
		Addr string `flag:"addr,ssh host:port"`
		Dir  string `flag:"dir,remote directory to upload files to"`
		Url  string `flag:"url,remote url base to open after upload"`
		Long bool   `flag:"long,generate long subdirectory name"`
	}{
		User: os.Getenv("USER"),
		Addr: "localhost:22",
		Dir:  "/tmp",
	}
	autoflags.Define(&params)
	flag.Parse()

	cfg, err := config(params.User)
	if err != nil {
		log.Fatal(err)
	}
	res, err := upload(params.Addr, params.Dir, params.Long, cfg, flag.Args())
	if res != "" {
		fmt.Println(res)
		if params.Url != "" {
			browser.OpenURL(path.Join(params.Url, path.Base(res)))
		}
	}
	if err != nil {
		log.Fatal(err)
	}
}