示例#1
0
func cpFile(src, dst string) error {
	s, err := os.Open(src)
	if err != nil {
		log.Warnln("sensor: monitor - cp - error opening source file =>", src)
		return err
	}
	defer s.Close()

	dstDir := utils.FileDir(dst)
	err = os.MkdirAll(dstDir, 0777)
	if err != nil {
		log.Warnln("sensor: monitor - dir error =>", err)
	}

	d, err := os.Create(dst)
	if err != nil {
		log.Warnln("sensor: monitor - cp - error opening dst file =>", dst)
		return err
	}

	srcFileInfo, err := s.Stat()
	if err == nil {
		d.Chmod(srcFileInfo.Mode())
	}

	if _, err := io.Copy(d, s); err != nil {
		d.Close()
		return err
	}
	return d.Close()
}
示例#2
0
文件: router.go 项目: axcoto-lab/moon
func (s *Server) mapRoutes() {
	r := s.router

	cwd, _ := os.Getwd()
	staticPath := path.Join(cwd, s.config.static)
	var staticURL string
	var staticBundleURL string
	if s.config.hot {
		// create the prefix necessary to load bundles from hmr server
		staticBundleURL = s.config.hmr
		staticURL = s.config.address
	} else {
		// ensure bundles exist if not hot reloading
		ensureBundles(s.config.js, s.config.style, staticPath)
		if s.config.dev {
			staticBundleURL = s.config.address
			staticURL = s.config.address
		} else {
			staticBundleURL = s.config.serve
			staticURL = s.config.serve
		}
	}
	staticBundleURL = path.Join(staticBundleURL, s.config.static)
	staticURL = path.Join(staticURL, s.config.static)
	log.Warnln(s.config.js)
	log.Warnln(s.config.static)
	// create the default app (the route used to serve the client app)
	app := defaultApp{}
	// load template
	f, err := os.Open(s.config.template)
	if err != nil {
		log.Errorln("Tpl err", err)
		os.Exit(1)
	}
	defer f.Close()
	b, err := ioutil.ReadAll(f)
	if err != nil {
		log.Errorln("Tpl read err", err)
		os.Exit(1)
	}
	tpl, err := template.New("app").Parse(string(b))
	if err != nil {
		log.Errorln("Tpl parse err", err)
		os.Exit(1)
	}
	app.data = map[string]interface{}{
		"Js":     path.Join(staticBundleURL, s.config.js),
		"Style":  path.Join(staticBundleURL, s.config.style),
		"Static": staticURL,
		"Hot":    s.config.hot,
	}
	log.Warnln(app.data)
	app.template = tpl

	// httprouter fileserver
	r.ServeFiles(path.Join(base(s.config.static), "*filepath"), http.Dir(staticPath))
	// if it's not an api call then we use the app, after first checking
	// if there's a file matching the route
	r.NotFound = app
}
示例#3
0
文件: host.go 项目: jemacom/hydra
func runHostCmd(cmd *cobra.Command, args []string) {
	router := httprouter.New()
	serverHandler := &server.Handler{}
	serverHandler.Start(c, router)

	if ok, _ := cmd.Flags().GetBool("dangerous-auto-logon"); ok {
		logrus.Warnln("Do not use flag --dangerous-auto-logon in production.")
		err := c.Persist()
		pkg.Must(err, "Could not write configuration file: %s", err)
	}

	http.Handle("/", router)

	var srv = http.Server{
		Addr: c.GetAddress(),
		TLSConfig: &tls.Config{
			Certificates: []tls.Certificate{
				getOrCreateTLSCertificate(cmd),
			},
		},
	}

	var err error
	logrus.Infof("Starting server on %s", c.GetAddress())
	if ok, _ := cmd.Flags().GetBool("force-dangerous-http"); ok {
		logrus.Warnln("HTTPS disabled. Never do this in production.")
		err = srv.ListenAndServe()
	} else {
		err = srv.ListenAndServeTLS("", "")
	}
	pkg.Must(err, "Could not start server: %s %s.", err)
}
示例#4
0
// AddSSHKeyToTags adds the ssh key in the tags
func AddSSHKeyToTags(ctx CommandContext, tags *[]string, image string) error {
	home, err := config.GetHomeDir()
	if err != nil {
		return fmt.Errorf("unable to find your home %v", err)
	}
	idRsa := filepath.Join(home, ".ssh", "id_rsa")
	if _, err := os.Stat(idRsa); err != nil {
		if os.IsNotExist(err) {
			logrus.Warnln("Unable to find your ~/.ssh/id_rsa")
			logrus.Warnln("Run 'ssh-keygen -t rsa'")
			return nil
		}
	}
	idRsa = strings.Join([]string{idRsa, ".pub"}, "")
	data, err := ioutil.ReadFile(idRsa)
	if err != nil {
		return fmt.Errorf("failed to read %v", err)
	}
	data[7] = '_'
	for i := range data {
		if data[i] == ' ' {
			data = data[:i]
			break
		}
	}
	*tags = append(*tags, strings.Join([]string{"AUTHORIZED_KEY", string(data[:len(data)])}, "="))
	return nil
}
示例#5
0
文件: default.go 项目: catalyzeio/cli
func CmdDefault(alias string, id IDefault) error {
	logrus.Warnln("The \"default\" command has been deprecated! It will be removed in a future version.")
	logrus.Warnln("Please specify \"-E\" on all commands instead of using the default.")
	err := id.Set(alias)
	if err != nil {
		return err
	}
	logrus.Printf("%s is now the default environment", alias)
	return nil
}
示例#6
0
文件: table.go 项目: tmc/adt
func (t *Table) readRecord() (Record, error) {
	r := Record{}
	bytes := make([]byte, t.RecordLength)
	if r, err := io.ReadFull(t.data, bytes); err != nil {
		log.Warn("didn't read enough: ", r, err)
		return nil, err
	}
	if string(bytes[:len(RecordMagicHeader)]) != RecordMagicHeader {
		//return nil, ErrMagicHeaderNotFound
	}
	for _, column := range t.Columns {
		value, err := ReadValue(bytes, column)
		// dbg:
		//valueBytes := bytes[column.Offset : column.Offset+column.Length]

		if asMemo, ok := value.(MemoField); ok {
			t.memoData.Seek(int64(asMemo.BlockOffset)*8, 0)
			data := make([]byte, asMemo.Length)
			if _, err := io.ReadFull(t.memoData, data); err != nil {
				log.Warnln("didn't read enough for memo field", column.Name, err)
				return nil, nil
			}
			value = data
		}

		if err != nil {
			return nil, err
		}
		r[column.Name] = value
	}
	return r, nil
}
示例#7
0
func (pool *streampool) pickupstreams(udp bool) []*upstream {
	pool.waitforalive()

	// pick udp and tcp equally
	pool.RLock()
	defer pool.RUnlock()

	// pick one of each

	switch {
	case udp && pool.udplen > 0:
		rn := int(atomic.AddUint32(&pool.rn, 1) - 1)
		return []*upstream{pool.udpool[rn%pool.udplen]}
	case pool.tcplen > 0 && pool.udplen > 0:
		// pick one of each
		rn := int(atomic.AddUint32(&pool.rn, 1) - 1)
		return []*upstream{
			pool.udpool[rn%pool.udplen],
			pool.tcpool[rn%pool.tcplen],
		}
	case pool.tcplen == 0 || pool.udplen == 0:
		// pick 2 alived
		rn := int(atomic.AddUint32(&pool.rn, 2) - 2)

		return []*upstream{
			pool.alived[rn%pool.alvlen],
			pool.alived[(rn+1)%pool.alvlen],
		}
	}
	logrus.Warnln("no upstream avalible for pick")
	return nil
}
示例#8
0
文件: func.go 项目: yuenmeiwan/quilt
func logImpl(ctx *evalCtx, args []ast) (ast, error) {
	level, ok := args[0].(astString)
	if !ok {
		return nil, fmt.Errorf("log level must be a string: %s\n", level)
	}

	msgAst, ok := args[1].(astString)
	if !ok {
		return nil, fmt.Errorf("log message must be a string: %s\n", args[1])
	}

	msg := string(msgAst)
	switch level {
	case "print":
		log.Println(msg)
	case "debug":
		log.Debugln(msg)
	case "info":
		log.Infoln(msg)
	case "warn":
		log.Warnln(msg)
	case "error":
		log.Errorln(msg)
	default:
		return nil,
			fmt.Errorf("log level must be one of "+
				"[print, info, debug, warn, error]: %s",
				level)
	}

	return astList{}, nil
}
func (p *TenantService) GetTenantByTenantId(tenantId string) (tenant *entity.Tenant, err error) {
	if !bson.IsObjectIdHex(tenantId) {
		logrus.Errorln("invalid object id for getTenantById: ", tenantId)
		err = errors.New("invalid object id for getTenantById")
		return
	}
	selector := bson.M{}
	selector["_id"] = bson.ObjectIdHex(tenantId)

	tenant = new(entity.Tenant)
	queryStruct := dao.QueryStruct{
		CollectionName: p.collectionName,
		Selector:       selector,
		Skip:           0,
		Limit:          0,
		Sort:           ""}

	err = dao.HandleQueryOne(tenant, queryStruct)
	if err != nil {
		logrus.Warnln("failed to get tenant by id %v", err)
		return
	}

	return
}
示例#10
0
文件: blog.go 项目: gssdromen/goblog
func (blog *Blog) generate(fileInfo os.FileInfo) {

	defer blog.wg.Done()

	//markdown input
	input, err := ioutil.ReadFile(config.SourceDir + "/articles/" + fileInfo.Name())
	if err != nil {
		log.Warnln("Can not open file: ", fileInfo.Name())
		return
	}

	//parse markdown to *Markdown obj
	markdown := mark.Mark(input)

	//extract article info
	article, err := getArticle(markdown, fileInfo)
	if err != nil {
		log.Error("[Format Error]: ", fileInfo.Name(), "; ", err)
		return
	}
	blog.articles = append(blog.articles, &article)

	markdown.Parts = markdown.Parts[1:]

	//transform markdown to html and output
	renderArticle(markdown, article)
}
示例#11
0
func (p *UserService) createAndInsertUser(userName string, password string, email string, tenanId string, roleId string, company string) (userId string, err error) {
	// var jsondocument interface{}
	currentUser, erro := p.getAllUserByName(userName)
	if erro != nil {
		logrus.Error("get all user by username err is %v", erro)
		return "", erro
	}
	if len(currentUser) != 0 {
		logrus.Infoln("user already exist! username:"******"create user error %v", err)
		return
	}
	userId = user.ObjectId.Hex()

	return
}
示例#12
0
func (p *UserService) GetUserByUserId(userId string) (user *entity.User, err error) {
	if !bson.IsObjectIdHex(userId) {
		logrus.Errorln("invalid object id for getUseerById: ", userId)
		err = errors.New("invalid object id for getUserById")
		return nil, err
	}
	selector := bson.M{}
	selector["_id"] = bson.ObjectIdHex(userId)

	user = new(entity.User)
	queryStruct := dao.QueryStruct{
		CollectionName: p.userCollectionName,
		Selector:       selector,
		Skip:           0,
		Limit:          0,
		Sort:           ""}

	err = dao.HandleQueryOne(user, queryStruct)

	if err != nil {
		logrus.Warnln("failed to get user by id %v", err)
		return
	}

	return
}
示例#13
0
文件: snvoting.go 项目: ineiti/prifi
func (sn *Node) StartGossip() {
	go func() {
		t := time.Tick(GOSSIP_TIME)
		for {
			select {
			case <-t:
				sn.viewmu.Lock()
				c := sn.HostListOn(sn.ViewNo)
				sn.viewmu.Unlock()
				if len(c) == 0 {
					log.Errorln(sn.Name(), "StartGossip: none in hostlist for view: ", sn.ViewNo, len(c))
					continue
				}
				sn.randmu.Lock()
				from := c[sn.Rand.Int()%len(c)]
				sn.randmu.Unlock()
				log.Errorln("Gossiping with: ", from)
				sn.CatchUp(int(atomic.LoadInt64(&sn.LastAppliedVote)+1), from)
			case <-sn.closed:
				log.Warnln("stopping gossip: closed")
				return
			}
		}
	}()
}
示例#14
0
// CreateAndInsertRole creat and insert the role items according to the given
// rolename and desc.
func (p *RoleService) createAndInsertRole(roleName string, desc string) (roleId string, err error) {
	role := &entity.Role{}
	role, err = p.getRoleByName(roleName)
	if err == nil {
		logrus.Infoln("role already exist! roleName: ", roleName)
		roleId = role.ObjectId.Hex()
		return
	}

	currentTime := dao.GetCurrentTime()
	objectId := bson.NewObjectId()
	role = &entity.Role{
		ObjectId:    objectId,
		Rolename:    roleName,
		Description: desc,
		TimeCreate:  currentTime,
		TimeUpdate:  currentTime,
	}

	err = dao.HandleInsert(p.collectionName, role)
	if err != nil {
		logrus.Warnln("create role error %v", err)
		return
	}
	roleId = role.ObjectId.Hex()
	return

}
示例#15
0
// handle packed data from client side as backend
func (s *serv) tcphandler(conn net.Conn) {

	dec := gob.NewDecoder(conn)
	enc := gob.NewEncoder(conn)

	// add to pool
	u := newUpstream(s.proto)
	u.encoder = enc
	u.decoder = dec

	defer func() {
		conn.Close()
		// remove from pool
		s.pool.remove(u)
	}()

	s.pool.append(u, 0)

	for {
		p := packet{}
		err := dec.Decode(&p)
		if err != nil {
			logrus.Warnln("packetHandler() Decode err:", err)
			break
		}

		if err := s.proc(u, &p); err != nil {
			logrus.WithError(err).Warn("serve send pong err")
			return
		}
	}
}
示例#16
0
文件: clear.go 项目: catalyzeio/cli
func CmdClear(privateKey, session, environments, defaultEnv, pods bool, settings *models.Settings) error {
	if defaultEnv {
		logrus.Warnln("The \"--default\" flag has been deprecated! It will be removed in a future version.")
	}
	if privateKey {
		settings.PrivateKeyPath = ""
	}
	if session {
		settings.SessionToken = ""
		settings.UsersID = ""
	}
	if environments {
		settings.Environments = map[string]models.AssociatedEnv{}
	}
	if defaultEnv {
		settings.Default = ""
	}
	if pods {
		settings.Pods = &[]models.Pod{}
	}
	config.SaveSettings(settings)
	if !privateKey && !session && !environments && !defaultEnv && !pods {
		logrus.Println("No settings were specified. To see available options, run \"catalyze clear --help\"")
	} else {
		logrus.Println("All specified settings have been cleared")
	}
	return nil
}
示例#17
0
文件: site.go 项目: fanyang01/crawler
func (s *SitesMeta) Handle(resp *crawler.Response) (follow bool, links []*crawler.Link) {
	if resp.NewURL.Path != "/robots.txt" {
		if s.Exist(resp.NewURL) {
			return true, nil
		}
	}
	var err error
	root := siteRoot(resp.NewURL)
	// url := resp.NewURL.String()

	s.Lock()
	site, ok := s.m[root]
	if !ok {
		if site, err = newSiteFromURL(resp.NewURL); err != nil {
			return
		}
		s.m[root] = site
	}
	site.Lock()
	defer site.Unlock()
	s.Unlock()

	if err = site.updateRobots(resp.StatusCode, resp.Content); err != nil {
		logrus.Warnln(err)
	}
	return true, urlToLink(site.sitemapURLs())
}
示例#18
0
// UserUpdateHandler parses the http request and updata a exist user.
// Usage :
//		PUT /v1/user/{ParamID}
// Params :
//		ParamID : storage identifier of user
// If successful,response code will be set to 201.
func (p *Resource) UserUpdateHandler(req *restful.Request, resp *restful.Response) {
	logrus.Infof("UserUpdateHanlder is called!")
	token := req.HeaderParameter("X-Auth-Token")
	id := req.PathParameter(ParamID)
	if len(id) <= 0 {
		logrus.Warnln("user id should not be null for update operation")
		response.WriteStatusError(services.COMMON_ERROR_INVALIDATE, errors.New("user id should not be null for update operation"), resp)
		return
	}

	newuser := entity.User{}

	// Populate the user data
	err := json.NewDecoder(req.Request.Body).Decode(&newuser)
	if err != nil {
		logrus.Errorf("convert body to user failed, error is %v", err)
		response.WriteStatusError(services.COMMON_ERROR_INVALIDATE, err, resp)
		return
	}

	created, id, errorCode, err := services.GetUserService().UserUpdate(token, newuser, id)
	if err != nil {
		response.WriteStatusError(errorCode, err, resp)
		return
	}

	p.successUpdate(id, created, req, resp)
}
示例#19
0
文件: blog.go 项目: flytiny/goblog
//Generate ...
func (blog *Blog) Generate() (err error) {
	//generate static article html
	files, err := blog.files()

	defer func() {
		//generate category.json
		b, _ := json.Marshal(blog.articles)
		err = ioutil.WriteFile("category.json", b, os.ModePerm)
		if err != nil {
			log.Warnln("[Generate Fail]: category.json")
		}

		//generate static category html
		By(func(i1, i2 interface{}) bool {
			return i1.(*Article).Date.Time.After(i2.(*Article).Date.Time)
		}).Sort(blog.articles)

		renderCategory(blog.articles)

		//generate home page
		renderHomePage(getOutputPath(*(blog.articles[0].(*Article))))
	}()

	if err != nil || len(files) == 0 {
		return
	}
	for _, file := range files {
		blog.wg.Add(1)
		go blog.generate(file)
	}

	blog.wg.Wait()

	return
}
// NewFromParameters construye un Scheduler a partir de un mapeo de parámetros
// Al menos se debe pasar como parametro address, ya que si no existe se retornara un error
// Si se pasa tlsverify como true los parametros tlscacert, tlscert y tlskey también deben existir
func NewFromParameters(params map[string]interface{}) (*Framework, error) {

	address, ok := params["address"]
	if !ok || fmt.Sprint(address) == "" {
		return nil, errors.New("Parametro address no existe")
	}

	authfile := dockerCfgPath()
	if af, ok := params["authfile"]; !ok || fmt.Sprint(af) == "" {
		log.Warnln("Parametro authfile no existe o está vacio, utilizando su valor por defecto", authfile)
	} else {
		authfile = fmt.Sprint(af)
	}

	tlsInfo, err := utils.NewTlsStruct(params)
	if err != nil {
		return nil, err
	}

	p := parameters{
		address:   fmt.Sprint(address),
		authfile:  authfile,
		tlsverify: tlsInfo.TlsVerify,
		tlscacert: tlsInfo.TlsCaCert,
		tlscert:   tlsInfo.TlsCert,
		tlskey:    tlsInfo.TlsKey,
	}

	return New(p)
}
示例#21
0
// doCleanup ...
// @isSkipHostCleanup : !!! should only be specified in case the host will be destroyed right after
//   the cleanup. 'will-be-destroyed' will leave the host as-it-is, uncleared!!
func doCleanup(configModel config.MachineConfigModel, isSkipHostCleanup string) error {
	log.Infof("==> doCleanup (mode: %s)", configModel.CleanupMode)

	if isSkipHostCleanup != "will-be-destroyed" {
		if configModel.CleanupMode == config.CleanupModeRollback {
			if err := utils.Run(MachineWorkdir.Get(), configModel.AllCmdEnvsForConfigType(MachineConfigTypeID.Get()), "vagrant", "snapshot", "pop", "--no-delete"); err != nil {
				return err
			}
		} else if configModel.CleanupMode == config.CleanupModeRecreate {
			if err := doRecreateCleanup(configModel); err != nil {
				return err
			}
		} else if configModel.CleanupMode == config.CleanupModeDestroy {
			if err := doDestroyCleanup(configModel); err != nil {
				return err
			}
		} else if configModel.CleanupMode == config.CleanupModeCustomCommand {
			if err := doCustomCleanup(configModel); err != nil {
				return err
			}
		} else {
			return fmt.Errorf("Unsupported CleanupMode: %s", configModel.CleanupMode)
		}
	} else {
		log.Warnln("Skipping Host Cleanup! This option should only be used if the Host is destroyed immediately after this cleanup!!")
	}

	if err := config.DeleteSSHFilesFromDir(MachineWorkdir.Get()); err != nil {
		return fmt.Errorf("Failed to delete SSH file from workdir: %s", err)
	}

	return nil
}
示例#22
0
func (p *UserService) UserDelete(token string, userId string) (errorCode string, err error) {
	if !bson.IsObjectIdHex(userId) {
		logrus.Errorln("invalid object id for UserDelete: ", userId)
		err = errors.New("invalid object id for UserDelete")
		return USER_ERROR_DELETE, err
	}

	code, err := GetTokenService().TokenValidate(token)
	if err != nil {
		return code, err
	}

	if authorized := GetAuthService().Authorize("delete_user", token, userId, p.userCollectionName); !authorized {
		logrus.Errorln("required opertion is not allowed!")
		return COMMON_ERROR_UNAUTHORIZED, errors.New("Required opertion is not authorized!")
	}

	clusters, errquery := GetClusterByUser(userId, token)
	if errquery != nil {
		logrus.Errorf("query cluster err is %v", errquery)
		return "", errors.New("query cluster is err")
	}
	if len(clusters) != 0 {
		logrus.Errorf("user has unterminated cluster")
		return USER_ERROR_EXISTCLUSTER, errors.New("Please terminated cluster first!")
	}

	selector := bson.M{}
	selector["_id"] = bson.ObjectIdHex(userId)

	user, err := p.GetUserById(userId)
	tenantid := user.TenantId

	err = dao.HandleDelete(p.userCollectionName, true, selector)
	if err != nil {
		logrus.Warnln("delete user error %v", err)
		return USER_ERROR_DELETE, err
	}

	err = GetTenantService().deleteTenantById(tenantid)
	if err != nil {
		logrus.Warnln("delete tenant error %v", err)
		return TENANT_ERROR_DELETE, err
	}

	return "", nil
}
示例#23
0
// RetrieveNode is a helper to retrieve the current node name of the agent.
func (c *Candidate) retrieveNode() {
	consul := c.consulClient()
	agent, err := consul.Agent().Self()
	if err != nil {
		logrus.Warnln("Unable to retrieve node name.")
	}
	c.node = agent["Config"]["NodeName"].(string)
}
示例#24
0
文件: logs.go 项目: catalyzeio/cli
// CmdLogs is a way to stream logs from Kibana to your local terminal. This is
// useful because Kibana is hard to look at because it splits every single
// log statement into a separate block that spans multiple lines so it's
// not very cohesive. This is intended to be similar to the `heroku logs`
// command.
func CmdLogs(queryString string, follow bool, hours, minutes, seconds int, envID string, settings *models.Settings, il ILogs, ip prompts.IPrompts, ie environments.IEnvironments, is services.IServices, isites sites.ISites) error {
	if follow && (hours > 0 || minutes > 0 || seconds > 0) {
		logrus.Warnln("Specifying \"logs -f\" in combination with \"--hours\", \"--minutes\", or \"--seconds\" has been deprecated!")
		logrus.Warnln("Please specify either \"-f\" or use \"--hours\", \"--minutes\", \"--seconds\" but not both. Support for \"-f\" and a specified time frame will be removed in a later version.")
	}
	env, err := ie.Retrieve(envID)
	if err != nil {
		return err
	}
	serviceProxy, err := is.RetrieveByLabel("service_proxy")
	if err != nil {
		return err
	}
	sites, err := isites.List(serviceProxy.ID)
	if err != nil {
		return err
	}
	domain := ""
	for _, site := range *sites {
		if strings.HasPrefix(site.Name, env.Namespace) {
			domain = site.Name
			break
		}
	}
	if domain == "" {
		return errors.New("Could not determine the fully qualified domain name of your environment. Please contact Catalyze Support at [email protected] with this error message to resolve this issue.")
	}
	if follow {
		if err := il.Watch(queryString, domain, settings.SessionToken); err != nil {
			logrus.Debugf("Error attempting to stream logs from logwatch: %s", err)
		} else {
			return nil
		}
	}
	from := 0
	offset := time.Duration(hours)*time.Hour + time.Duration(minutes)*time.Minute + time.Duration(seconds)*time.Second
	timestamp := time.Now().In(time.UTC).Add(-1 * offset)
	from, timestamp, err = il.Output(queryString, settings.SessionToken, domain, follow, hours, minutes, seconds, from, timestamp, time.Now(), env)
	if err != nil {
		return err
	}
	if follow {
		return il.Stream(queryString, settings.SessionToken, domain, follow, hours, minutes, seconds, from, timestamp, env)
	}
	return nil
}
示例#25
0
func main() {
	if len(os.Args) != 3 {
		logrus.Fatalln("Usage: ddgo <src> <dest>")
	}
	src := os.Args[1]
	dst := os.Args[2]
	fd, err := os.OpenFile(src, os.O_RDONLY, 0)
	if err != nil {
		logrus.Fatalln("failed to open src:", err)
	}
	defer fd.Close()
	srcLen, err := fd.Seek(0, 2)
	if err != nil {
		logrus.Fatalln(err)
	}
	_, err = fd.Seek(0, 0)
	if err != nil {
		logrus.Fatalln(err)
	}

	bar := pb.New64(srcLen)
	bar.SetUnits(pb.U_BYTES)
	bar.ShowSpeed = true
	bar.ShowTimeLeft = true

	out, err := os.OpenFile(dst, os.O_WRONLY|syscall.O_DIRECT, 0777)
	if err != nil {
		logrus.Fatalln("failed to open dst:", err)
	}
	defer out.Close()

	dstLen, err := out.Seek(0, 2)
	if err != nil {
		logrus.Fatalln(err)
	}
	_, err = out.Seek(0, 0)
	if err != nil {
		logrus.Fatalln(err)
	}

	if dstLen < srcLen {
		bar.Total = dstLen
	}

	bar.Start()
	if dstLen < srcLen {
		logrus.Warnln("destination device too small, not all bytes will be copied")
		_, err = io.Copy(io.MultiWriter(bar, out), io.LimitReader(fd, dstLen))
	} else {
		_, err = io.Copy(io.MultiWriter(bar, out), fd)
	}
	if err != nil {
		logrus.Fatalln("copy failed:", err)
	}
	bar.Finish()
	fd.Close()
	out.Close()
}
示例#26
0
// PerformStartupChecks executes the suite of startup checks that are run before the bot
// connects to the server.
func PerformStartupChecks() {
	logrus.WithFields(logrus.Fields{
		"num_services": fmt.Sprintf("%d", len(DJ.AvailableServices)),
	}).Infoln("Checking for availability of services...")

	for i := len(DJ.AvailableServices) - 1; i >= 0; i-- {
		if err := DJ.AvailableServices[i].CheckAPIKey(); err != nil {
			name := DJ.AvailableServices[i].GetReadableName()
			logrus.WithFields(logrus.Fields{
				"service": name,
				"error":   err.Error(),
			}).Warnln("A startup check discovered an issue. The service will be disabled.")

			// Remove service from enabled services.
			DJ.AvailableServices = append(DJ.AvailableServices[:i], DJ.AvailableServices[i+1:]...)
		}
	}

	if len(DJ.AvailableServices) == 0 {
		logrus.Fatalln("The bot cannot continue as no services are enabled.")
	}

	if err := checkYouTubeDLInstallation(); err != nil {
		logrus.Fatalln("youtube-dl is either not installed or is not discoverable in $PATH. youtube-dl is required to download audio.")
	}
	if viper.GetString("defaults.player_command") == "ffmpeg" {
		if err := checkFfmpegInstallation(); err != nil {
			logrus.Fatalln("ffmpeg is either not installed or is not discoverable in $PATH. If you would like to use avconv instead, change the defaults.player_command value in the configuration file.")
		}
	} else if viper.GetString("defaults.player_command") == "avconv" {
		if err := checkAvconvInstallation(); err != nil {
			logrus.Fatalln("avconv is either not installed or is not discoverable in $PATH. If you would like to use ffmpeg instead, change the defaults.player_command value in the configuration file.")
		}
	} else {
		logrus.Fatalln("The player command provided in the configuration file is invalid. Valid choices are: \"ffmpeg\", \"avconv\".")
	}

	if err := checkAria2Installation(); err != nil {
		logrus.Warnln("aria2 is not installed or is not discoverable in $PATH. The bot will still partially work, but some services will not work properly.")
	}

	if err := checkOpenSSLInstallation(); err != nil {
		logrus.Warnln("openssl is not installed or is not discoverable in $PATH. p12 certificate files will not work.")
	}
}
示例#27
0
func checkIsBitriseToolInstalled(toolname, minVersion string, isInstall bool) error {
	doInstall := func() error {
		installCmdLines := []string{
			"curl -L https://github.com/bitrise-io/" + toolname + "/releases/download/" + minVersion + "/" + toolname + "-$(uname -s)-$(uname -m) > /usr/local/bin/" + toolname,
			"chmod +x /usr/local/bin/" + toolname,
		}
		officialGithub := "https://github.com/bitrise-io/" + toolname
		fmt.Println()
		log.Warnln("No supported " + toolname + " version found.")
		log.Infoln("You can find more information about "+toolname+" on it's official GitHub page:", officialGithub)
		fmt.Println()

		// Install
		log.Infoln("Installing...")
		fmt.Println(strings.Join(installCmdLines, "\n"))
		if err := bitrise.RunBashCommandLines(installCmdLines); err != nil {
			return err
		}

		// check again
		return checkIsBitriseToolInstalled(toolname, minVersion, false)
	}

	// check whether installed
	progInstallPth, err := CheckProgramInstalledPath(toolname)
	if err != nil {
		if !isInstall {
			return err
		}

		return doInstall()
	}
	verStr, err := bitrise.RunCommandAndReturnStdout(toolname, "-version")
	if err != nil {
		log.Infoln("")
		return errors.New("Failed to get version")
	}

	// version check
	isVersionOk, err := bitrise.IsVersionGreaterOrEqual(verStr, minVersion)
	if err != nil {
		log.Error("Failed to validate installed version")
		return err
	}
	if !isVersionOk {
		log.Warn("Installed "+toolname+" found, but not a supported version: ", verStr)
		if !isInstall {
			return errors.New("Failed to install required version.")
		}
		log.Warn("Updating...")
		return doInstall()
	}

	log.Infoln(" * "+colorstring.Green("[OK]")+" "+toolname+" :", progInstallPth)
	log.Infoln("        version :", verStr)
	return nil
}
示例#28
0
func CmdDisassociate(alias string, id IDisassociate) error {
	err := id.Disassociate(alias)
	if err != nil {
		return err
	}
	logrus.Warnln("Your existing git remote *has not* been removed. You must do this manually.")
	logrus.Println("Association cleared.")
	return nil
}
示例#29
0
// Leader returns the node of the current cluster leader. This returns an empty string if there is no leader.
func (c *Candidate) Leader() string {
	consul := c.consulClient()
	kv, _, err := consul.KV().Get(c.LeadershipKey, nil)
	if kv == nil || err != nil {
		logrus.Warnln("There is no leader.")
		return ""
	}
	return string(kv.Value)
}
示例#30
0
文件: updater.go 项目: catalyzeio/cli
func (u *Updater) update() error {
	path, err := osext.Executable()
	if err != nil {
		return err
	}
	old, err := os.Open(path)
	if err != nil {
		return err
	}
	defer old.Close()

	err = u.FetchInfo()
	if err != nil {
		return err
	}
	if u.Info.Version <= u.CurrentVersion {
		return nil
	}

	bin, err := u.fetchAndVerifyFullBin()
	if err != nil {
		if err == ErrHashMismatch {
			logrus.Warnln("update: hash mismatch from full binary")
		} else {
			logrus.Warnln("update: error fetching full binary,", err)
		}
		logrus.Warnln("update: please update your CLI manually by downloading the latest version for your OS here https://github.com/catalyzeio/cli/releases")
		return err
	}

	// close the old binary before installing because on windows
	// it can't be renamed if a handle to the file is still open
	old.Close()

	err, errRecover := up.FromStream(bytes.NewBuffer(bin))
	if errRecover != nil {
		return fmt.Errorf("update and recovery errors: %q %q", err, errRecover)
	}
	if err != nil {
		return err
	}
	logrus.Println("update: your CLI has been successfully updated!")
	return nil
}