Beispiel #1
0
func downloadReleaseAsset(r *github.ReleaseAsset, newName *string, newPath *string) {
	var outDir string
	if newPath == nil {
		outDir = binDir()
	} else {
		outDir = *newPath
	}

	downloadUrlString := *r.BrowserDownloadURL

	log.Infof("Downloading release asset: %s", downloadUrlString)
	log.Infof("Copying to: %s", outDir)

	downloadUrl, err := url.Parse(downloadUrlString)
	if err != nil {
		log.Fatalf("Error: Could not parse URL: %v", err)
	}

	var fileName string
	if newName == nil {
		_, fileName = path.Split(downloadUrl.Path)
	} else {
		fileName = *newName
	}

	outName := outDir + "/" + fileName
	out, err := os.Create(outName)
	if err != nil {
		log.Fatalf("Error: Could not create local file: %v", err)
	}

	defer out.Close()
	resp, err := http.Get(downloadUrlString)
	if err != nil {
		log.Fatalf("Error: Could not get remote file: %v", err)
	}
	defer resp.Body.Close()
	bar := ioprogress.DrawTextFormatBar(20)
	progressFunc := ioprogress.DrawTerminalf(os.Stdout, func(progress, total int64) string {
		return fmt.Sprintf("%s %s %20s", fileName, bar(progress, total), ioprogress.DrawTextFormatBytes(progress, total))
	})

	progress := &ioprogress.Reader{
		Reader:       resp.Body,
		Size:         resp.ContentLength,
		DrawInterval: time.Millisecond,
		DrawFunc:     progressFunc,
	}

	_, err = io.Copy(out, progress)
	if err != nil {
		log.Fatalf("Error: Could not copy local file: %v", err)
	}

	err = os.Chmod(outName, 0755)
	if err != nil {
		log.Fatalf("Error: Could not make %s executable. Try with (sudo)?", outName)
	}
}
Beispiel #2
0
func binDir() string {
	dir, err := os.Getwd()
	if err != nil {
		log.Fatalf("Error: No working directory")
	}
	log.Infof("GOOS: %s", runtime.GOOS)

	switch runtime.GOOS {
	case "darwin":
		fallthrough
	case "dragonfly":
		fallthrough
	case "linux":
		fallthrough
	case "freebsd":
		fallthrough
	case "netbsd":
		fallthrough
	case "openbsd":
		dir = "/usr/local/bin"
		break
	default:
		break
	}
	return dir
}
Beispiel #3
0
// Handle is the SSH client entrypoint, it takes a net.Conn
// instance and handle all the ssh and ssh2docker stuff
func (s *Server) Handle(netConn net.Conn) error {
	if err := s.Init(); err != nil {
		return err
	}

	log.Debugf("Server.Handle netConn=%v", netConn)
	// Initialize a Client object
	conn, chans, reqs, err := ssh.NewServerConn(netConn, s.SshConfig)

	if err != nil {
		log.Infof("Received disconnect from %s: 11: Bye Bye [preauth]", netConn.RemoteAddr().String())
		return err
	}
	client := NewClient(conn, chans, reqs, s)

	// Handle requests
	if err = client.HandleRequests(); err != nil {
		return err
	}

	// Handle channels
	if err = client.HandleChannels(); err != nil {
		return err
	}
	return nil
}
Beispiel #4
0
// Action is the default cli action to execute
func Action(c *cli.Context) {
	// Initialize the SSH server
	server, err := ssh2docker.NewServer()
	if err != nil {
		log.Fatalf("Cannot create server: %v", err)
	}

	// Restrict list of allowed images
	if c.String("allowed-images") != "" {
		server.AllowedImages = strings.Split(c.String("allowed-images"), ",")
	}

	// Configure server
	server.DefaultShell = c.String("shell")
	server.DockerRunArgsInline = c.String("docker-run-args")
	server.DockerExecArgsInline = c.String("docker-exec-args")
	server.NoJoin = c.Bool("no-join")
	server.CleanOnStartup = c.Bool("clean-on-startup")
	server.PasswordAuthScript = c.String("password-auth-script")
	server.PublicKeyAuthScript = c.String("publickey-auth-script")
	server.LocalUser = c.String("local-user")
	server.Banner = c.String("banner")

	// Register the SSH host key
	hostKey := c.String("host-key")
	switch hostKey {
	case "built-in":
		hostKey = DefaultHostKey
	case "system":
		hostKey = "/etc/ssh/ssh_host_rsa_key"
	}
	err = server.AddHostKey(hostKey)
	if err != nil {
		log.Fatalf("Cannot add host key: %v", err)
	}

	// Bind TCP socket
	bindAddress := c.String("bind")
	listener, err := net.Listen("tcp", bindAddress)
	if err != nil {
		log.Fatalf("Failed to start listener on %q: %v", bindAddress, err)
	}
	log.Infof("Listening on %q", bindAddress)

	// Initialize server
	if err = server.Init(); err != nil {
		log.Fatalf("Failed to initialize the server: %v", err)
	}

	// Accept new clients
	for {
		conn, err := listener.Accept()
		if err != nil {
			log.Errorf("Accept failed: %v", err)
			continue
		}
		go server.Handle(conn)
	}
}
Beispiel #5
0
func TestInfo(t *testing.T) {
	h := memory.New()
	log.SetHandler(h)

	log.Infof("logged in %s", "Tobi")

	e := h.Entries[0]
	assert.Equal(t, e.Message, "logged in Tobi")
	assert.Equal(t, e.Level, log.InfoLevel)
}
Beispiel #6
0
// Upgrade the current `version` of apex to the latest.
func Upgrade(version string) error {
	log.Infof("current release is v%s", version)

	// fetch releases
	gh := github.NewClient(nil)
	releases, _, err := gh.Repositories.ListReleases("apex", "apex", nil)
	if err != nil {
		return err
	}

	// see if it's new
	latest := releases[0]
	log.Infof("latest release is %s", *latest.TagName)

	if (*latest.TagName)[1:] == version {
		log.Infof("you're up to date :)")
		return nil
	}

	asset := findAsset(&latest)
	if asset == nil {
		return errors.New("cannot find binary for your system")
	}

	// create tmp file
	tmpPath := filepath.Join(os.TempDir(), "apex-upgrade")
	f, err := os.OpenFile(tmpPath, os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0755)
	if err != nil {
		return err
	}

	// download binary
	log.Infof("downloading %s", *asset.BrowserDownloadURL)
	res, err := http.Get(*asset.BrowserDownloadURL)
	if err != nil {
		return err
	}
	defer res.Body.Close()

	// copy it down
	_, err = io.Copy(f, res.Body)
	if err != nil {
		return err
	}

	// replace it
	cmdPath, err := exec.LookPath("apex")
	if err != nil {
		return err
	}

	log.Infof("replacing %s", cmdPath)
	err = os.Rename(tmpPath, cmdPath)
	if err != nil {
		return err
	}

	log.Infof("visit https://github.com/apex/apex/releases for the changelog")
	return nil
}
Beispiel #7
0
// NewClient initializes a new client
func NewClient(conn *ssh.ServerConn, chans <-chan ssh.NewChannel, reqs <-chan *ssh.Request, server *Server) *Client {
	client := Client{
		Idx:        clientCounter,
		ClientID:   conn.RemoteAddr().String(),
		ChannelIdx: 0,
		Conn:       conn,
		Chans:      chans,
		Reqs:       reqs,
		Server:     server,

		// Default ClientConfig, will be overwritten if a hook is used
		Config: &ClientConfig{
			ImageName:              strings.Replace(conn.User(), "_", "/", -1),
			RemoteUser:             "******",
			AuthenticationMethod:   "noauth",
			AuthenticationComment:  "",
			AuthenticationAttempts: 0,
			Env:     envhelper.Environment{},
			Command: make([]string, 0),
		},
	}

	if server.LocalUser != "" {
		client.Config.IsLocal = client.Config.ImageName == server.LocalUser
	}

	if _, found := server.ClientConfigs[client.ClientID]; !found {
		server.ClientConfigs[client.ClientID] = client.Config
	}

	client.Config = server.ClientConfigs[conn.RemoteAddr().String()]
	client.Config.Env.ApplyDefaults()

	clientCounter++

	remoteAddr := strings.Split(client.ClientID, ":")
	log.Infof("Accepted %s for %s from %s port %s ssh2: %s", client.Config.AuthenticationMethod, conn.User(), remoteAddr[0], remoteAddr[1], client.Config.AuthenticationComment)
	return &client
}
Beispiel #8
0
func main() {
	renameFlag := flag.String("r", "", "-r [newname]")
	pathFlag := flag.String("p", "", "-p [/some/path/]")
	dryRunFlag := flag.Bool("d", false, "-d")
	flag.Usage = func() {
		println(USAGE)
	}

	flag.Parse()
	args := flag.Args()

	log.Infof("Flags: rename(%s), path(%s), dry(%t)", *renameFlag, *pathFlag, *dryRunFlag)
	log.Infof("Args : %s", strings.Join(args, ", "))

	if len(args) < 1 {
		log.Fatal(USAGE)
	}

	project := strings.TrimSpace(args[0])
	if project == "" {
		log.Fatal(USAGE)
	}

	parts := strings.Split(project, "/")
	if len(parts) != 2 {
		log.Fatal(USAGE)
	}

	owner := strings.TrimSpace(parts[0])
	repo := strings.TrimSpace(parts[1])
	if owner == "" || repo == "" {
		log.Fatal(USAGE)
	}

	projectUrl := fmt.Sprintf("github.com/%s/%s", owner, repo)

	client := github.NewClient(nil)

	log.Infof("Grabbing from %s...", project)

	_, resp, err := client.Repositories.Get(owner, repo)
	if err != nil {
		if resp == nil {
			log.Fatalf("Error: Cannot reach %s", projectUrl)
		}

		if resp.StatusCode == 404 {
			log.Fatalf("Error: Project does not exist: %s", projectUrl)
		} else {
			log.Fatalf("Error: Unknown error (%d) reaching: %s", resp.StatusCode, projectUrl)
		}
	}

	release, resp, err := client.Repositories.GetLatestRelease(owner, repo)
	if err != nil {
		if resp.StatusCode == 404 {
			log.Infof("No official releases yet. Checking pre-release tags...")
			tags, _, err := client.Repositories.ListTags(owner, repo, nil)
			if err != nil || len(tags) < 1 {
				log.Fatalf(ERR_NO_RELEASES, err)
			}

			tag := tags[0]
			log.Infof("Latest tag: %s (%s)", *tag.Name, *tag.Commit.SHA)

			release, resp, err = client.Repositories.GetReleaseByTag(owner, repo, *tag.Name)
			if err != nil || len(tags) < 1 {
				log.Fatalf(ERR_NO_RELEASES, err)
			}
		}
	}

	assets := release.Assets
	var asset github.ReleaseAsset

	switch len(assets) {
	case 0:
		log.Fatal("Error: No assets to download")
		break
	case 1:
		asset = assets[0]
		break
	default:
		log.Info("Release Assets:")
		for i, a := range assets {
			log.Infof(" (%d) %s (%s)", i+1, *a.Name, *a.BrowserDownloadURL)
		}

		reader := bufio.NewReader(os.Stdin)
		fmt.Print("Which asset would you like to download? ")
		choice, _ := reader.ReadString('\n')
		choice = strings.TrimSpace(choice)
		choiceInt, err := strconv.Atoi(choice)
		if err != nil {
			log.Fatalf("Error: You must select an asset to download")
		}
		println("")
		asset = assets[choiceInt-1]

		break
	}

	if *dryRunFlag {
		log.Info("Dry-run completed")
	} else {
		downloadReleaseAsset(&asset, renameFlag, pathFlag)
	}
}
Beispiel #9
0
	log.SetHandler(text.New(os.Stdout))
	log.SetLevel(log.InfoLevel)

	godotenv.Load()
	path := os.Getenv("PATH_MWML")

	Describe("Selectors", func() {
		log.SetLevel(log.InfoLevel)
		mw := &mwQuery{}
		_ = mw.importMotiveWaveXML(path)
		markup, _ := mw.parse()

		It("Ongoing", func() {

			price := &Point{T: time.Now()}

			helper := NewHelper("My", markup, price)

			degrees := []DegreeType{Minute, Minuette, Subminuette, Micro, Submicro}

			sel := NewWavesSelector("Selector", markup, price)
			sel.Ongoing().Info()

			for _, degree := range degrees {
				log.Infof("In correction %s = %t", degree, helper.InCorrection(degree))
			}

		})
	})
})
Beispiel #10
0
// Unstructured logging is supported, but not recommended since it is hard to query.
func Example_unstructured() {
	log.Infof("%s logged in", "Tobi")
}
Beispiel #11
0
// Infof level formatted message.
func Infof(msg string, v ...interface{}) {
	apexlog.Infof(msg, v...)
}
Beispiel #12
0
func connectMQTT() {
	log.Infof("Connecting to The Things Network...")
	if token := mqttClient.Connect(); token.Wait() && token.Error() != nil {
		panic(token.Error())
	}
}