Esempio n. 1
0
func newCacheService() {
	CacheAdapter = Cfg.MustValue("cache", "ADAPTER", "memory")
	if EnableRedis {
		log.Info("Redis Enabled")
	}
	if EnableMemcache {
		log.Info("Memcache Enabled")
	}

	switch CacheAdapter {
	case "memory":
		CacheConfig = fmt.Sprintf(`{"interval":%d}`, Cfg.MustInt("cache", "INTERVAL", 60))
	case "redis", "memcache":
		CacheConfig = fmt.Sprintf(`{"conn":"%s"}`, Cfg.MustValue("cache", "HOST"))
	default:
		qlog.Fatalf("Unknown cache adapter: %s\n", CacheAdapter)
	}

	var err error
	Cache, err = cache.NewCache(CacheAdapter, CacheConfig)
	if err != nil {
		qlog.Fatalf("Init cache system failed, adapter: %s, config: %s, %v\n",
			CacheAdapter, CacheConfig, err)
	}

	log.Info("Cache Service Enabled")
}
Esempio n. 2
0
func CheckRepoStats() {
	if isCheckingRepos {
		return
	}
	isCheckingRepos = true
	defer func() { isCheckingRepos = false }()

	// Check count watchers
	results_watch, err := x.Query("SELECT r.id FROM `repository` r WHERE r.num_watches!=(SELECT count(*) FROM `watch` WHERE repo_id=r.id)")
	if err != nil {
		log.Error(4, "select repository check 'watch': %v", err)
	}
	for _, repo_id := range results_watch {
		log.Info("updating repository count 'watch'")
		repoID := com.StrTo(repo_id["id"]).MustInt64()
		_, err := x.Exec("UPDATE `repository` SET num_watches=(SELECT count(*) FROM `watch` WHERE repo_id=?) WHERE id=?", repoID, repoID)
		if err != nil {
			log.Error(4, "update repository check 'watch', repo %v: %v", repo_id, err)
		}
	}

	// Check count stars
	results_star, err := x.Query("SELECT s.id FROM `repository` s WHERE s.num_stars!=(SELECT count(*) FROM `star` WHERE repo_id=s.id)")
	if err != nil {
		log.Error(4, "select repository check 'star': %v", err)
	}
	for _, repo_id := range results_star {
		log.Info("updating repository count 'star'")
		repoID := com.StrTo(repo_id["id"]).MustInt64()
		_, err := x.Exec("UPDATE `repository` SET .num_stars=(SELECT count(*) FROM `star` WHERE repo_id=?) WHERE id=?", repoID, repoID)
		if err != nil {
			log.Error(4, "update repository check 'star', repo %v: %v", repo_id, err)
		}
	}
}
Esempio n. 3
0
// initRepoCommit temporarily changes with work directory.
func initRepoCommit(tmpPath string, sig *git.Signature) error {
	gitInitLocker.Lock()
	defer gitInitLocker.Unlock()

	// Change work directory.
	curPath, err := os.Getwd()
	if err != nil {
		return err
	} else if err = os.Chdir(tmpPath); err != nil {
		return err
	}
	defer os.Chdir(curPath)

	var stderr string
	if _, stderr, err = com.ExecCmd("git", "add", "--all"); err != nil {
		return err
	}
	log.Info("stderr(1): %s", stderr)
	if _, stderr, err = com.ExecCmd("git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
		"-m", "Init commit"); err != nil {
		return err
	}
	log.Info("stderr(2): %s", stderr)
	if _, stderr, err = com.ExecCmd("git", "push", "origin", "master"); err != nil {
		return err
	}
	log.Info("stderr(3): %s", stderr)
	return nil
}
Esempio n. 4
0
// GlobalInit is for global configuration reload-able.
func GlobalInit() {
	setting.NewConfigContext()
	log.Trace("Custom path: %s", setting.CustomPath)
	log.Trace("Log path: %s", setting.LogRootPath)
	mailer.NewMailerContext()
	models.LoadModelsConfig()
	NewServices()

	if setting.InstallLock {
		models.LoadRepoConfig()
		models.NewRepoContext()

		if err := models.NewEngine(); err != nil {
			log.Fatal(4, "Fail to initialize ORM engine: %v", err)
		}

		models.HasEngine = true
		cron.NewCronContext()
		models.InitDeliverHooks()
		log.NewGitLogger(path.Join(setting.LogRootPath, "http.log"))
	}
	if models.EnableSQLite3 {
		log.Info("SQLite3 Supported")
	}
	if models.EnableTidb {
		log.Info("TiDB Supported")
	}
	checkRunMode()
}
Esempio n. 5
0
// GlobalInit is for global configuration reload-able.
func GlobalInit() {
	setting.NewContext()
	log.Trace("Custom path: %s", setting.CustomPath)
	log.Trace("Log path: %s", setting.LogRootPath)
	models.LoadConfigs()
	NewServices()

	if setting.InstallLock {
		models.LoadRepoConfig()
		models.NewRepoContext()

		if err := models.NewEngine(); err != nil {
			log.Fatal(4, "Fail to initialize ORM engine: %v", err)
		}

		models.HasEngine = true
		cron.NewContext()
		models.InitDeliverHooks()
		models.InitTestPullRequests()
		log.NewGitLogger(path.Join(setting.LogRootPath, "http.log"))
	}
	if models.EnableSQLite3 {
		log.Info("SQLite3 Supported")
	}
	if models.EnableTidb {
		log.Info("TiDB Supported")
	}
	checkRunMode()

	if setting.StartSSHServer {
		ssh.Listen(setting.SSHPort)
		log.Info("SSH server started on :%v", setting.SSHPort)
	}
}
Esempio n. 6
0
func newLogService() {
	log.Info("%s %s", AppName, AppVer)

	// Get and check log mode.
	LogModes = strings.Split(Cfg.MustValue("log", "MODE", "console"), ",")
	LogConfigs = make([]string, len(LogModes))
	for i, mode := range LogModes {
		mode = strings.TrimSpace(mode)
		modeSec := "log." + mode
		if _, err := Cfg.GetSection(modeSec); err != nil {
			log.Fatal("Unknown log mode: %s", mode)
		}

		// Log level.
		levelName := Cfg.MustValueRange("log."+mode, "LEVEL", "Trace",
			[]string{"Trace", "Debug", "Info", "Warn", "Error", "Critical"})
		level, ok := logLevels[levelName]
		if !ok {
			log.Fatal("Unknown log level: %s", levelName)
		}

		// Generate log configuration.
		switch mode {
		case "console":
			LogConfigs[i] = fmt.Sprintf(`{"level":%s}`, level)
		case "file":
			logPath := Cfg.MustValue(modeSec, "FILE_NAME", path.Join(LogRootPath, "gogs.log"))
			os.MkdirAll(path.Dir(logPath), os.ModePerm)
			LogConfigs[i] = fmt.Sprintf(
				`{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level,
				logPath,
				Cfg.MustBool(modeSec, "LOG_ROTATE", true),
				Cfg.MustInt(modeSec, "MAX_LINES", 1000000),
				1<<uint(Cfg.MustInt(modeSec, "MAX_SIZE_SHIFT", 28)),
				Cfg.MustBool(modeSec, "DAILY_ROTATE", true),
				Cfg.MustInt(modeSec, "MAX_DAYS", 7))
		case "conn":
			LogConfigs[i] = fmt.Sprintf(`{"level":"%s","reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level,
				Cfg.MustBool(modeSec, "RECONNECT_ON_MSG"),
				Cfg.MustBool(modeSec, "RECONNECT"),
				Cfg.MustValueRange(modeSec, "PROTOCOL", "tcp", []string{"tcp", "unix", "udp"}),
				Cfg.MustValue(modeSec, "ADDR", ":7020"))
		case "smtp":
			LogConfigs[i] = fmt.Sprintf(`{"level":"%s","username":"******","password":"******","host":"%s","sendTos":"%s","subject":"%s"}`, level,
				Cfg.MustValue(modeSec, "USER", "*****@*****.**"),
				Cfg.MustValue(modeSec, "PASSWD", "******"),
				Cfg.MustValue(modeSec, "HOST", "127.0.0.1:25"),
				Cfg.MustValue(modeSec, "RECEIVERS", "[]"),
				Cfg.MustValue(modeSec, "SUBJECT", "Diagnostic message from serve"))
		case "database":
			LogConfigs[i] = fmt.Sprintf(`{"level":"%s","driver":"%s","conn":"%s"}`, level,
				Cfg.MustValue(modeSec, "DRIVER"),
				Cfg.MustValue(modeSec, "CONN"))
		}

		log.NewLogger(Cfg.MustInt64("log", "BUFFER_LEN", 10000), mode, LogConfigs[i])
		log.Info("Log Mode: %s(%s)", strings.Title(mode), levelName)
	}
}
Esempio n. 7
0
func newLogService() {
	// Get and check log mode.
	LogMode = Cfg.MustValue("log", "MODE", "console")
	modeSec := "log." + LogMode
	if _, err := Cfg.GetSection(modeSec); err != nil {
		qlog.Fatalf("Unknown log mode: %s\n", LogMode)
	}

	// Log level.
	levelName := Cfg.MustValue("log."+LogMode, "LEVEL", "Trace")
	level, ok := logLevels[levelName]
	if !ok {
		qlog.Fatalf("Unknown log level: %s\n", levelName)
	}

	// Generate log configuration.
	switch LogMode {
	case "console":
		LogConfig = fmt.Sprintf(`{"level":%s}`, level)
	case "file":
		logPath := Cfg.MustValue(modeSec, "FILE_NAME", "log/gogs.log")
		os.MkdirAll(path.Dir(logPath), os.ModePerm)
		LogConfig = fmt.Sprintf(
			`{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level,
			logPath,
			Cfg.MustBool(modeSec, "LOG_ROTATE", true),
			Cfg.MustInt(modeSec, "MAX_LINES", 1000000),
			1<<uint(Cfg.MustInt(modeSec, "MAX_SIZE_SHIFT", 28)),
			Cfg.MustBool(modeSec, "DAILY_ROTATE", true),
			Cfg.MustInt(modeSec, "MAX_DAYS", 7))
	case "conn":
		LogConfig = fmt.Sprintf(`{"level":"%s","reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level,
			Cfg.MustBool(modeSec, "RECONNECT_ON_MSG", false),
			Cfg.MustBool(modeSec, "RECONNECT", false),
			Cfg.MustValue(modeSec, "PROTOCOL", "tcp"),
			Cfg.MustValue(modeSec, "ADDR", ":7020"))
	case "smtp":
		LogConfig = fmt.Sprintf(`{"level":"%s","username":"******","password":"******","host":"%s","sendTos":"%s","subject":"%s"}`, level,
			Cfg.MustValue(modeSec, "USER", "*****@*****.**"),
			Cfg.MustValue(modeSec, "PASSWD", "******"),
			Cfg.MustValue(modeSec, "HOST", "127.0.0.1:25"),
			Cfg.MustValue(modeSec, "RECEIVERS", "[]"),
			Cfg.MustValue(modeSec, "SUBJECT", "Diagnostic message from serve"))
	case "database":
		LogConfig = fmt.Sprintf(`{"level":"%s","driver":"%s","conn":"%s"}`, level,
			Cfg.MustValue(modeSec, "Driver"),
			Cfg.MustValue(modeSec, "CONN"))
	}

	log.Info("%s %s", AppName, AppVer)
	log.NewLogger(Cfg.MustInt64("log", "BUFFER_LEN", 10000), LogMode, LogConfig)
	log.Info("Log Mode: %s(%s)", strings.Title(LogMode), levelName)
}
Esempio n. 8
0
// github && google && ...
func SocialSignIn(tokens oauth2.Tokens) {
	transport := &oauth.Transport{}
	transport.Token = &oauth.Token{
		AccessToken:  tokens.Access(),
		RefreshToken: tokens.Refresh(),
		Expiry:       tokens.ExpiryTime(),
		Extra:        tokens.ExtraData(),
	}

	// Github API refer: https://developer.github.com/v3/users/
	// FIXME: need to judge url
	type GithubUser struct {
		Id    int    `json:"id"`
		Name  string `json:"login"`
		Email string `json:"email"`
	}

	// Make the request.
	scope := "https://api.github.com/user"
	r, err := transport.Client().Get(scope)
	if err != nil {
		log.Error("connect with github error: %s", err)
		// FIXME: handle error page
		return
	}
	defer r.Body.Close()

	user := &GithubUser{}
	err = json.NewDecoder(r.Body).Decode(user)
	if err != nil {
		log.Error("Get: %s", err)
	}
	log.Info("login: %s", user.Name)
	// FIXME: login here, user email to check auth, if not registe, then generate a uniq username
}
Esempio n. 9
0
File: issue.go Progetto: chadoe/gogs
func (c *Comment) AfterDelete() {
	_, err := DeleteAttachmentsByComment(c.ID, true)

	if err != nil {
		log.Info("Could not delete files for comment %d on issue #%d: %s", c.ID, c.IssueID, err)
	}
}
Esempio n. 10
0
func DeleteUser(ctx *middleware.Context, params martini.Params) {
	ctx.Data["Title"] = "Delete Account"
	ctx.Data["PageIsUsers"] = true

	log.Info("delete")
	uid, err := base.StrTo(params["userid"]).Int()
	if err != nil {
		ctx.Handle(404, "admin.user.EditUser", err)
		return
	}

	u, err := models.GetUserById(int64(uid))
	if err != nil {
		ctx.Handle(500, "admin.user.EditUser", err)
		return
	}

	if err = models.DeleteUser(u); err != nil {
		switch err {
		case models.ErrUserOwnRepos:
			ctx.Flash.Error("This account still has ownership of repository, owner has to delete or transfer them first.")
			ctx.Redirect("/admin/users/" + params["userid"])
		default:
			ctx.Handle(500, "admin.user.DeleteUser", err)
		}
		return
	}
	log.Trace("%s User deleted by admin(%s): %s", ctx.Req.RequestURI,
		ctx.User.LowerName, ctx.User.LowerName)

	ctx.Redirect("/admin/users")
}
Esempio n. 11
0
func (i *Issue) AfterDelete() {
	_, err := DeleteAttachmentsByIssue(i.Id, true)

	if err != nil {
		log.Info("Could not delete files for issue #%d: %s", i.Id, err)
	}
}
Esempio n. 12
0
// GenerateRandomAvatar generates a random avatar for user.
func (u *User) GenerateRandomAvatar() error {
	seed := u.Email
	if len(seed) == 0 {
		seed = u.Name
	}

	img, err := avatar.RandomImage([]byte(seed))
	if err != nil {
		return fmt.Errorf("RandomImage: %v", err)
	}
	if err = os.MkdirAll(filepath.Dir(u.CustomAvatarPath()), os.ModePerm); err != nil {
		return fmt.Errorf("MkdirAll: %v", err)
	}
	fw, err := os.Create(u.CustomAvatarPath())
	if err != nil {
		return fmt.Errorf("Create: %v", err)
	}
	defer fw.Close()

	if err = jpeg.Encode(fw, img, nil); err != nil {
		return fmt.Errorf("Encode: %v", err)
	}

	log.Info("New random avatar created: %d", u.Id)
	return nil
}
Esempio n. 13
0
func newSessionService() {
	SessionProvider = Cfg.MustValue("session", "PROVIDER", "memory")

	SessionConfig = new(session.Config)
	SessionConfig.ProviderConfig = Cfg.MustValue("session", "PROVIDER_CONFIG")
	SessionConfig.CookieName = Cfg.MustValue("session", "COOKIE_NAME", "i_like_gogits")
	SessionConfig.CookieSecure = Cfg.MustBool("session", "COOKIE_SECURE")
	SessionConfig.EnableSetCookie = Cfg.MustBool("session", "ENABLE_SET_COOKIE", true)
	SessionConfig.GcIntervalTime = Cfg.MustInt64("session", "GC_INTERVAL_TIME", 86400)
	SessionConfig.SessionLifeTime = Cfg.MustInt64("session", "SESSION_LIFE_TIME", 86400)
	SessionConfig.SessionIDHashFunc = Cfg.MustValue("session", "SESSION_ID_HASHFUNC", "sha1")
	SessionConfig.SessionIDHashKey = Cfg.MustValue("session", "SESSION_ID_HASHKEY")

	if SessionProvider == "file" {
		os.MkdirAll(path.Dir(SessionConfig.ProviderConfig), os.ModePerm)
	}

	var err error
	SessionManager, err = session.NewManager(SessionProvider, *SessionConfig)
	if err != nil {
		qlog.Fatalf("Init session system failed, provider: %s, %v\n",
			SessionProvider, err)
	}

	log.Info("Session Service Enabled")
}
Esempio n. 14
0
func (s *SocialCloudron) UserInfo(token *oauth2.Token, _ *url.URL) (*BasicUserInfo, error) {
	log.Info("UserInfo for cloudron being invoked!")
	transport := s.opts.NewTransportFromToken(token)
	var data struct {
		Id    string `json:"id"`
		Name  string `json:"username"`
		Email string `json:"email"`
	}

	reqUrl := setting.Cfg.Section("oauth.cloudron").Key("CLOUDRON_ORIGIN").MustString("EpicFailValue") + "/api/v1/profile"
	r, err := transport.Client().Get(reqUrl)
	if err != nil {
		return nil, err
	}
	defer r.Body.Close()

	if err = json.NewDecoder(r.Body).Decode(&data); err != nil {
		return nil, err
	}
	return &BasicUserInfo{
		Identity: data.Id,
		Name:     data.Name,
		Email:    data.Email,
	}, nil
}
Esempio n. 15
0
func newLdapService() {
	Service.LdapAuth = Cfg.MustBool("security", "LDAP_AUTH", false)
	if !Service.LdapAuth {
		return
	}

	nbsrc := 0
	for _, v := range Cfg.GetSectionList() {
		if matched, _ := regexp.MatchString("(?i)^LDAPSOURCE.*", v); matched {
			ldapname := Cfg.MustValue(v, "name", v)
			ldaphost := Cfg.MustValue(v, "host")
			ldapport := Cfg.MustInt(v, "port", 389)
			ldapbasedn := Cfg.MustValue(v, "basedn", "dc=*,dc=*")
			ldapattribute := Cfg.MustValue(v, "attribute", "mail")
			ldapfilter := Cfg.MustValue(v, "filter", "(*)")
			ldapmsadsaformat := Cfg.MustValue(v, "MSADSAFORMAT", "%s")
			ldap.AddSource(ldapname, ldaphost, ldapport, ldapbasedn, ldapattribute, ldapfilter, ldapmsadsaformat)
			nbsrc++
			log.Debug("%s added as LDAP source", ldapname)
		}
	}
	if nbsrc == 0 {
		log.Warn("No valide LDAP found, LDAP Authentication NOT enabled")
		Service.LdapAuth = false
		return
	}

	log.Info("LDAP Authentication Enabled")
}
Esempio n. 16
0
func renderVerticalHtmlTable(m []yaml.MapSlice) string {
	var ms yaml.MapSlice
	var mi yaml.MapItem
	var table string

	for _, ms = range m {
		table += `<table data="yaml-metadata">`
		for _, mi = range ms {
			key := mi.Key
			value := mi.Value

			table += `<tr>`
			if key != nil && reflect.TypeOf(key).String() == "yaml.MapSlice" {
				key = renderHorizontalHtmlTable(key.(yaml.MapSlice))
			} else if key != nil && reflect.TypeOf(key).String() == "[]interface {}" {
				var ks string
				for _, ki := range key.([]interface{}) {
					log.Info("KI: %v", ki)
					log.Info("Type: %s", reflect.TypeOf(ki).String())
					ks += renderHorizontalHtmlTable(ki.(yaml.MapSlice))
				}
				key = ks
			}
			table += fmt.Sprintf("<td>%v</td>", key)

			if value != nil && reflect.TypeOf(value).String() == "yaml.MapSlice" {
				value = renderHorizontalHtmlTable(value.(yaml.MapSlice))
			} else if value != nil && reflect.TypeOf(value).String() == "[]interface {}" {
				value = value.([]interface{})
				v := make([]yaml.MapSlice, len(value.([]interface{})))
				for i, vs := range value.([]interface{}) {
					v[i] = vs.(yaml.MapSlice)
				}
				value = renderVerticalHtmlTable(v)
			}
			if key == "slug" {
				value = fmt.Sprintf(`<a href="content/%v.md">%v</a>`, value, value)
			}
			table += fmt.Sprintf("<td>%v</td>", value)

			table += `</tr>`
		}
		table += "</table>"
	}

	return table
}
Esempio n. 17
0
// Migrate database to current version
func Migrate(x *xorm.Engine) error {
	if err := x.Sync(new(Version)); err != nil {
		return fmt.Errorf("sync: %v", err)
	}

	currentVersion := &Version{Id: 1}
	has, err := x.Get(currentVersion)
	if err != nil {
		return fmt.Errorf("get: %v", err)
	} else if !has {
		// If the user table does not exist it is a fresh installation and we
		// can skip all migrations.
		needsMigration, err := x.IsTableExist("user")
		if err != nil {
			return err
		}
		if needsMigration {
			isEmpty, err := x.IsTableEmpty("user")
			if err != nil {
				return err
			}
			// If the user table is empty it is a fresh installation and we can
			// skip all migrations.
			needsMigration = !isEmpty
		}
		if !needsMigration {
			currentVersion.Version = int64(_MIN_DB_VER + len(migrations))
		}

		if _, err = x.InsertOne(currentVersion); err != nil {
			return fmt.Errorf("insert: %v", err)
		}
	}

	v := currentVersion.Version
	if _MIN_DB_VER > v {
		log.Fatal(4, "Gogs no longer supports auto-migration from your previously installed version. Please try to upgrade to a lower version first, then upgrade to current version.")
		return nil
	}

	if int(v-_MIN_DB_VER) > len(migrations) {
		// User downgraded Gogs.
		currentVersion.Version = int64(len(migrations) + _MIN_DB_VER)
		_, err = x.Id(1).Update(currentVersion)
		return err
	}
	for i, m := range migrations[v-_MIN_DB_VER:] {
		log.Info("Migration: %s", m.Description())
		if err = m.Migrate(x); err != nil {
			return fmt.Errorf("do migrate: %v", err)
		}
		currentVersion.Version = v + int64(i) + 1
		if _, err = x.Id(1).Update(currentVersion); err != nil {
			return err
		}
	}
	return nil
}
Esempio n. 18
0
// Check run mode(Default of martini is Dev).
func checkRunMode() {
	switch base.Cfg.MustValue("", "RUN_MODE") {
	case "prod":
		martini.Env = martini.Prod
	case "test":
		martini.Env = martini.Test
	}
	log.Info("Run Mode: %s", strings.Title(martini.Env))
}
Esempio n. 19
0
func checkRunMode() {
	switch setting.Cfg.Section("").Key("RUN_MODE").String() {
	case "prod":
		macaron.Env = macaron.PROD
		macaron.ColorLog = false
		setting.ProdMode = true
	}
	log.Info("Run Mode: %s", strings.Title(macaron.Env))
}
Esempio n. 20
0
func newNotifyMailService() {
	if !Cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").MustBool() {
		return
	} else if MailService == nil {
		log.Warn("Notify Mail Service: Mail Service is not enabled")
		return
	}
	Service.EnableNotifyMail = true
	log.Info("Notify Mail Service Enabled")
}
Esempio n. 21
0
func checkRunMode() {
	switch setting.Cfg.Section("").Key("RUN_MODE").String() {
	case "prod":
		macaron.Env = macaron.PROD
		setting.ProdMode = true
	case "test":
		macaron.Env = macaron.TEST
	}
	log.Info("Run Mode: %s", strings.Title(macaron.Env))
}
Esempio n. 22
0
func checkRunMode() {
	switch setting.Cfg.MustValue("", "RUN_MODE") {
	case "prod":
		macaron.Env = macaron.PROD
		setting.ProdMode = true
	case "test":
		macaron.Env = macaron.TEST
	}
	log.Info("Run Mode: %s", strings.Title(macaron.Env))
}
Esempio n. 23
0
func newRegisterMailService() {
	if !Cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").MustBool() {
		return
	} else if MailService == nil {
		log.Warn("Register Mail Service: Mail Service is not enabled")
		return
	}
	Service.RegisterEmailConfirm = true
	log.Info("Register Mail Service Enabled")
}
Esempio n. 24
0
func newCacheService() {
	CacheAdapter = Cfg.Section("cache").Key("ADAPTER").In("memory", []string{"memory", "redis", "memcache"})
	if EnableRedis {
		log.Info("Redis Supported")
	}
	if EnableMemcache {
		log.Info("Memcache Supported")
	}

	switch CacheAdapter {
	case "memory":
		CacheInternal = Cfg.Section("cache").Key("INTERVAL").MustInt(60)
	case "redis", "memcache":
		CacheConn = strings.Trim(Cfg.Section("cache").Key("HOST").String(), "\" ")
	default:
		log.Fatal(4, "Unknown cache adapter: %s", CacheAdapter)
	}

	log.Info("Cache Service Enabled")
}
Esempio n. 25
0
func newCacheService() {
	CacheAdapter = Cfg.MustValueRange("cache", "ADAPTER", "memory", []string{"memory", "redis", "memcache"})
	if EnableRedis {
		log.Info("Redis Enabled")
	}
	if EnableMemcache {
		log.Info("Memcache Enabled")
	}

	switch CacheAdapter {
	case "memory":
		CacheInternal = Cfg.MustInt("cache", "INTERVAL", 60)
	case "redis", "memcache":
		CacheConn = strings.Trim(Cfg.MustValue("cache", "HOST"), "\" ")
	default:
		log.Fatal(4, "Unknown cache adapter: %s", CacheAdapter)
	}

	log.Info("Cache Service Enabled")
}
Esempio n. 26
0
// GlobalInit is for global configuration reload-able.
func GlobalInit() {
	setting.NewContext()
	log.Trace("Custom path: %s", setting.CustomPath)
	log.Trace("Log path: %s", setting.LogRootPath)
	models.LoadConfigs()
	NewServices()

	if setting.InstallLock {
		highlight.NewContext()
		markdown.BuildSanitizer()

		models.LoadRepoConfig()
		models.NewRepoContext()
		if err := models.NewEngine(); err != nil {
			log.Fatal(4, "Fail to initialize ORM engine: %v", err)
		}
		models.HasEngine = true

		// Booting long running goroutines.
		cron.NewContext()
		models.InitSyncMirrors()
		models.InitDeliverHooks()
		models.InitTestPullRequests()
		log.NewGitLogger(path.Join(setting.LogRootPath, "http.log"))
	}
	if models.EnableSQLite3 {
		log.Info("SQLite3 Supported")
	}
	if models.EnableTiDB {
		log.Info("TiDB Supported")
	}
	if setting.SupportMiniWinService {
		log.Info("Builtin Windows Service Supported")
	}
	checkRunMode()

	if setting.InstallLock && setting.SSH.StartBuiltinServer {
		ssh.Listen(setting.SSH.ListenPort)
		log.Info("SSH server started on :%v", setting.SSH.ListenPort)
	}
}
Esempio n. 27
0
File: ssh.go Progetto: nafrente/gogs
func handleServerConn(keyId string, chans <-chan ssh.NewChannel) {
	for newChan := range chans {
		if newChan.ChannelType() != "session" {
			newChan.Reject(ssh.UnknownChannelType, "unknown channel type")
			continue
		}
		channel, requests, err := newChan.Accept()
		if err != nil {
			log.Error(3, "Could not accept channel: %v", err)
			continue
		}

		go func(in <-chan *ssh.Request) {
			defer channel.Close()
			for req := range in {
				ok, payload := false, strings.TrimLeft(string(req.Payload), "\x00&")
				fmt.Println("Request:", req.Type, req.WantReply, payload)
				if req.WantReply {
					fmt.Println(req.Reply(true, nil))
				}
				switch req.Type {
				case "env":
					args := strings.Split(strings.Replace(payload, "\x00", "", -1), "\v")
					if len(args) != 2 {
						break
					}
					args[0] = strings.TrimLeft(args[0], "\x04")
					_, _, err := com.ExecCmdBytes("env", args[0]+"="+args[1])
					if err != nil {
						log.Error(3, "env: %v", err)
						channel.Stderr().Write([]byte(err.Error()))
						break
					}
					ok = true
				case "exec":
					os.Setenv("SSH_ORIGINAL_COMMAND", strings.TrimLeft(payload, "'("))
					log.Info("Payload: %v", strings.TrimLeft(payload, "'("))
					cmd := exec.Command("/Users/jiahuachen/Applications/Go/src/github.com/gogits/gogs/gogs", "serv", "key-"+keyId)
					cmd.Stdout = channel
					cmd.Stdin = channel
					cmd.Stderr = channel.Stderr()
					if err := cmd.Run(); err != nil {
						log.Error(3, "exec: %v", err)
					} else {
						ok = true
					}
				}
				fmt.Println("Done:", ok)
			}
			fmt.Println("Done!!!")
		}(requests)
	}
}
Esempio n. 28
0
func newMailService() {
	// Check mailer setting.
	if Cfg.MustBool("mailer", "ENABLED") {
		MailService = &Mailer{
			Name:   Cfg.MustValue("mailer", "NAME", AppName),
			Host:   Cfg.MustValue("mailer", "HOST", "127.0.0.1:25"),
			User:   Cfg.MustValue("mailer", "USER", "*****@*****.**"),
			Passwd: Cfg.MustValue("mailer", "PASSWD", "******"),
		}
		log.Info("Mail Service Enabled")
	}
}
Esempio n. 29
0
func newSessionService() {
	SessionConfig.Provider = Cfg.Section("session").Key("PROVIDER").In("memory",
		[]string{"memory", "file", "redis", "mysql"})
	SessionConfig.ProviderConfig = strings.Trim(Cfg.Section("session").Key("PROVIDER_CONFIG").String(), "\" ")
	SessionConfig.CookieName = Cfg.Section("session").Key("COOKIE_NAME").MustString("i_like_gogits")
	SessionConfig.CookiePath = AppSubUrl
	SessionConfig.Secure = Cfg.Section("session").Key("COOKIE_SECURE").MustBool()
	SessionConfig.Gclifetime = Cfg.Section("session").Key("GC_INTERVAL_TIME").MustInt64(86400)
	SessionConfig.Maxlifetime = Cfg.Section("session").Key("SESSION_LIFE_TIME").MustInt64(86400)

	log.Info("Session Service Enabled")
}
Esempio n. 30
0
func newMailService() {
	// Check mailer setting.
	if !Cfg.MustBool("mailer", "ENABLED") {
		return
	}

	MailService = &Mailer{
		Name:   Cfg.MustValue("mailer", "NAME", AppName),
		Host:   Cfg.MustValue("mailer", "HOST"),
		User:   Cfg.MustValue("mailer", "USER"),
		Passwd: Cfg.MustValue("mailer", "PASSWD"),
	}
	log.Info("Mail Service Enabled")
}