Пример #1
0
func isWatching(channel string, name string) bool {
	chanName := strings.Replace(channel, "#", "", 1)
	url := "http://tmi.twitch.tv/group/user/" + chanName + "/chatters"
	response, err := http.Get(url)
	if err != nil {
		log.Fatalf("Cannot get URL response: %s\n", err.Error())
	}
	defer response.Body.Close()
	data, err := ioutil.ReadAll(response.Body)
	if err != nil {
		log.Fatalf("Cannot read URL response: %s\n", err.Error())
	}
	var parsed map[string]interface{}
	p := json.Unmarshal(data, &parsed)
	if p != nil {
		log.Fatalf("Parse error: %s\n", err.Error())
	}
	chats := parsed["chatters"].(map[string]interface{})
	views := chats["viewers"].([]interface{})
	mods := chats["moderators"].([]interface{})
	for _, b := range views {
		if b == strings.ToLower(name) {
			return true
		}
	}
	for _, b := range mods {
		if b == strings.ToLower(name) {
			return true
		}
	}
	return false
}
Пример #2
0
// RealType takes 'XmlName' and finds its real concrete type in our Protocol.
// It is an error if we can't find such a type.
func (t *Translation) RealType(p *Protocol) Type {
	// Check to see if there is a namespace. If so, strip it and use it to
	// make sure we only look for a type in that protocol.
	namespace, typeName := "", t.XmlName()
	if ni := strings.Index(t.XmlName(), ":"); ni > -1 {
		namespace, typeName = strings.ToLower(typeName[:ni]), typeName[ni+1:]
	}

	if len(namespace) == 0 || namespace == strings.ToLower(p.Name) {
		for _, typ := range p.Types {
			if typeName == typ.XmlName() {
				return typ
			}
		}
	}
	for _, imp := range p.Imports {
		if len(namespace) == 0 || namespace == strings.ToLower(imp.Name) {
			for _, typ := range imp.Types {
				if typeName == typ.XmlName() {
					return typ
				}
			}
		}
	}
	panic("Could not find real type for translation type: " + t.XmlName())
}
Пример #3
0
// KindToResource converts Kind to a resource name.
func KindToResource(kind unversioned.GroupVersionKind, mixedCase bool) (plural, singular unversioned.GroupVersionResource) {
	kindName := kind.Kind
	if len(kindName) == 0 {
		return
	}
	if mixedCase {
		// Legacy support for mixed case names
		singular = kind.GroupVersion().WithResource(strings.ToLower(kindName[:1]) + kindName[1:])
	} else {
		singular = kind.GroupVersion().WithResource(strings.ToLower(kindName))
	}

	singularName := singular.Resource
	if strings.HasSuffix(singularName, "endpoints") || strings.HasSuffix(singularName, "securitycontextconstraints") {
		plural = singular
	} else {
		switch string(singularName[len(singularName)-1]) {
		case "s":
			plural = kind.GroupVersion().WithResource(singularName + "es")
		case "y":
			plural = kind.GroupVersion().WithResource(strings.TrimSuffix(singularName, "y") + "ies")
		default:
			plural = kind.GroupVersion().WithResource(singularName + "s")
		}
	}
	return
}
Пример #4
0
func isTreamCreationAllowed(c *Context, email string) bool {

	email = strings.ToLower(email)

	if utils.Cfg.TeamSettings.DisableTeamCreation {
		c.Err = model.NewAppError("isTreamCreationAllowed", "Team creation has been disabled. Please ask your systems administrator for details.", "")
		return false
	}

	// commas and @ signs are optional
	// can be in the form of "@corp.mattermost.com, mattermost.com mattermost.org" -> corp.mattermost.com mattermost.com mattermost.org
	domains := strings.Fields(strings.TrimSpace(strings.ToLower(strings.Replace(strings.Replace(utils.Cfg.TeamSettings.RestrictCreationToDomains, "@", " ", -1), ",", " ", -1))))

	matched := false
	for _, d := range domains {
		if strings.HasSuffix(email, "@"+d) {
			matched = true
			break
		}
	}

	if len(utils.Cfg.TeamSettings.RestrictCreationToDomains) > 0 && !matched {
		c.Err = model.NewAppError("isTreamCreationAllowed", "Email must be from a specific domain (e.g. @example.com). Please ask your systems administrator for details.", "")
		return false
	}

	return true
}
Пример #5
0
// NewConnection validates the upgrade response, creating and returning a new
// httpstream.Connection if there were no errors.
func (s *SpdyRoundTripper) NewConnection(resp *http.Response) (httpstream.Connection, error) {
	connectionHeader := strings.ToLower(resp.Header.Get(httpstream.HeaderConnection))
	upgradeHeader := strings.ToLower(resp.Header.Get(httpstream.HeaderUpgrade))
	if (resp.StatusCode != http.StatusSwitchingProtocols) || !strings.Contains(connectionHeader, strings.ToLower(httpstream.HeaderUpgrade)) || !strings.Contains(upgradeHeader, strings.ToLower(HeaderSpdy31)) {
		defer resp.Body.Close()
		responseError := ""
		responseErrorBytes, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			responseError = "unable to read error from server response"
		} else {
			// TODO: I don't belong here, I should be abstracted from this class
			if obj, _, err := api.Codecs.UniversalDecoder().Decode(responseErrorBytes, nil, &unversioned.Status{}); err == nil {
				if status, ok := obj.(*unversioned.Status); ok {
					return nil, &apierrors.StatusError{ErrStatus: *status}
				}
			}
			responseError = string(responseErrorBytes)
			responseError = strings.TrimSpace(responseError)
		}

		return nil, fmt.Errorf("unable to upgrade connection: %s", responseError)
	}

	return NewClientConnection(s.conn)
}
Пример #6
0
func (c *baseController) Prepare() {
	controllerName, actionName := c.GetControllerAndAction()
	c.controllerName = strings.ToLower(controllerName[0 : len(controllerName)-10])
	c.actionName = strings.ToLower(actionName)
	c.auth()
	// c.checkPermission()
}
Пример #7
0
func (v *Viper) searchMap(source map[string]interface{}, path []string) interface{} {

	if len(path) == 0 {
		return source
	}

	var ok bool
	var next interface{}
	for k, v := range source {
		if strings.ToLower(k) == strings.ToLower(path[0]) {
			ok = true
			next = v
			break
		}
	}

	if ok {
		switch next.(type) {
		case map[interface{}]interface{}:
			return v.searchMap(cast.ToStringMap(next), path[1:])
		case map[string]interface{}:
			// Type assertion is safe here since it is only reached
			// if the type of `next` is the same as the type being asserted
			return v.searchMap(next.(map[string]interface{}), path[1:])
		default:
			return next
		}
	} else {
		return nil
	}
}
Пример #8
0
func (p Pages) groupByDateField(sorter func(p Pages) Pages, formatter func(p *Page) string, order ...string) (PagesGroup, error) {
	if len(p) < 1 {
		return nil, nil
	}

	sp := sorter(p)

	if !(len(order) > 0 && (strings.ToLower(order[0]) == "asc" || strings.ToLower(order[0]) == "rev" || strings.ToLower(order[0]) == "reverse")) {
		sp = sp.Reverse()
	}

	date := formatter(sp[0])
	var r []PageGroup
	r = append(r, PageGroup{Key: date, Pages: make(Pages, 0)})
	r[0].Pages = append(r[0].Pages, sp[0])

	i := 0
	for _, e := range sp[1:] {
		date = formatter(e)
		if r[i].Key.(string) != date {
			r = append(r, PageGroup{Key: date})
			i++
		}
		r[i].Pages = append(r[i].Pages, e)
	}
	return r, nil
}
Пример #9
0
func (statement *Statement) processIdParam() {

	if statement.IdParam != nil {
		i := 0
		colCnt := len(statement.RefTable.ColumnsSeq)
		for _, elem := range *(statement.IdParam) {
			for ; i < colCnt; i++ {
				colName := statement.RefTable.ColumnsSeq[i]
				col := statement.RefTable.Columns[strings.ToLower(colName)]
				if col.IsPrimaryKey {
					statement.And(fmt.Sprintf("%v=?", col.Name), elem)
					i++
					break
				}
			}
		}

		// !nashtsai! REVIEW what if statement.IdParam has insufficient pk item? handle it
		// as empty string for now, so this will result sql exec failed instead of unexpected
		// false update/delete
		for ; i < colCnt; i++ {
			colName := statement.RefTable.ColumnsSeq[i]
			col := statement.RefTable.Columns[strings.ToLower(colName)]
			if col.IsPrimaryKey {
				statement.And(fmt.Sprintf("%v=?", col.Name), "")
			}
		}
	}
}
Пример #10
0
func (p *Filter) Push(k string) {
	partResult := make(ResultItemSlice, 0)
	s := "/"
	if runtime.GOOS == "windows" {
		s = "\\"
	}
	for _, v := range p.Results {
		if v.Index >= len(v.Line.Cs) {
			continue
		}
		l := v.Line.GetString()
		if config.GetConfig().FuzzyFindMode == config.NameMode && v.Index == 0 {
			li := strings.LastIndex(l, s)
			if li != -1 && li <= len(l)-1 {
				if li == len(l)-1 {
					v.Index = li
				} else {
					v.Index = li + 1
				}
			}
		}
		k = strings.ToLower(k)
		l = strings.ToLower(l[v.Index:])
		if strings.Contains(l, k) {
			v.Index += strings.Index(l, k) + len(k)
			partResult = append(partResult, v)
		}
	}
	if config.GetConfig().DirectoryMode == config.AllMode {
		sort.Sort(partResult)
	}
	p.Results = partResult
}
Пример #11
0
func (orm *Model) Delete(output interface{}) (int64, error) {
	defer orm.InitModel()
	orm.ScanPK(output)
	results, err := scanStructIntoMap(output)
	if err != nil {
		return 0, err
	}

	if orm.TableName == "" {
		orm.TableName = getTableName(StructName(output))
	}
	id := results[strings.ToLower(orm.PrimaryKey)]
	condition := fmt.Sprintf("%v%v%v='%v'", orm.QuoteIdentifier, strings.ToLower(orm.PrimaryKey), orm.QuoteIdentifier, id)
	statement := fmt.Sprintf("DELETE FROM %v%v%v WHERE %v",
		orm.QuoteIdentifier,
		orm.TableName,
		orm.QuoteIdentifier,
		condition)
	if OnDebug {
		fmt.Println(statement)
		fmt.Println(orm)
	}
	res, err := orm.Exec(statement)
	if err != nil {
		return -1, err
	}
	Affectid, err := res.RowsAffected()

	if err != nil {
		return -1, err
	}
	return Affectid, nil
}
Пример #12
0
func (p *Page) getParam(key string, stringToLower bool) interface{} {
	v := p.Params[strings.ToLower(key)]

	if v == nil {
		return nil
	}

	switch v.(type) {
	case bool:
		return cast.ToBool(v)
	case string:
		if stringToLower {
			return strings.ToLower(cast.ToString(v))
		}
		return cast.ToString(v)
	case int64, int32, int16, int8, int:
		return cast.ToInt(v)
	case float64, float32:
		return cast.ToFloat64(v)
	case time.Time:
		return cast.ToTime(v)
	case []string:
		if stringToLower {
			return helpers.SliceToLower(v.([]string))
		}
		return v.([]string)
	case map[string]interface{}: // JSON and TOML
		return v
	case map[interface{}]interface{}: // YAML
		return v
	}

	jww.ERROR.Printf("GetParam(\"%s\"): Unknown type %s\n", key, reflect.TypeOf(v))
	return nil
}
Пример #13
0
func newValidatorImpl(domains []string, usersFile string,
	done <-chan bool, onUpdate func()) func(string) bool {
	validUsers := NewUserMap(usersFile, done, onUpdate)

	var allowAll bool
	for i, domain := range domains {
		if domain == "*" {
			allowAll = true
			continue
		}
		domains[i] = fmt.Sprintf("@%s", strings.ToLower(domain))
	}

	validator := func(email string) bool {
		email = strings.ToLower(email)
		valid := false
		for _, domain := range domains {
			valid = valid || strings.HasSuffix(email, domain)
		}
		if !valid {
			valid = validUsers.IsValid(email)
		}
		if allowAll {
			valid = true
		}
		return valid
	}
	return validator
}
Пример #14
0
func (i *input) showHelp() {
	examples := make([]string, len(uiCommands))
	maxLen := 0

	for ix, cmd := range uiCommands {
		line := "/" + cmd.name
		prototype := reflect.TypeOf(cmd.prototype)
		for j := 0; j < prototype.NumField(); j++ {
			if strings.HasPrefix(string(prototype.Field(j).Tag), "flag:") {
				line += " [--" + strings.ToLower(string(prototype.Field(j).Tag[5:])) + "]"
			} else {
				line += " <" + strings.ToLower(prototype.Field(j).Name) + ">"
			}
		}
		if l := len(line); l > maxLen {
			maxLen = l
		}
		examples[ix] = line
	}

	for ix, cmd := range uiCommands {
		line := examples[ix]
		numSpaces := 1 + (maxLen - len(line))
		for j := 0; j < numSpaces; j++ {
			line += " "
		}
		line += cmd.desc
		info(i.term, i.tc, line)
	}
}
Пример #15
0
func newLogger(endpoint, strLevel, strFacility, tag string) EventLevelLogger {
	// figure priority
	level, err := stringToLevel(strLevel)

	if err != nil {
		panic("Initializing in ln logger: " + err.Error())
	}

	// figure out endpoint
	if strings.ToLower(endpoint) == "stderr" {
		// create a logger that writes to stderr, and we dont' care about the facility
		return newJSONLogger(newWriterLogger(os.Stderr, tag), level, -1)
	} else if strings.ToLower(endpoint) == "syslog" {
		facility, err := stringToFacility(strFacility)

		if err != nil {
			panic("Initializing in ln logger : " + err.Error())
		}

		syslogger := newBSyslogger(bsyslog.Priority(facility), tag)
		return newJSONLogger(syslogger, level, facility)
	} else {
		file, err := os.OpenFile(endpoint, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
		if err != nil {
			panic("Initializing ln logger: could not create endpoint " + endpoint + ", error: " + err.Error())
		}
		return newJSONLogger(newWriterLogger(file, tag), level, -1)
	}
}
Пример #16
0
func getPackagePath(curpath string) (packpath string) {
	gopath := os.Getenv("GOPATH")
	Debugf("gopath:%s", gopath)
	if gopath == "" {
		ColorLog("[ERRO] you should set GOPATH in the env")
		os.Exit(2)
	}

	appsrcpath := ""
	haspath := false
	wgopath := filepath.SplitList(gopath)

	for _, wg := range wgopath {
		wg, _ = filepath.EvalSymlinks(path.Join(wg, "src"))

		if filepath.HasPrefix(strings.ToLower(curpath), strings.ToLower(wg)) {
			haspath = true
			appsrcpath = wg
			break
		}
	}

	if !haspath {
		ColorLog("[ERRO] Can't generate application code outside of GOPATH '%s'\n", gopath)
		os.Exit(2)
	}
	packpath = strings.Join(strings.Split(curpath[len(appsrcpath)+1:], string(filepath.Separator)), "/")
	return
}
// getCanonicalHeaders generate a list of request headers with their values
func (r *rpcSignature) getCanonicalHeaders(signedHeaders map[string][]string) string {
	var headers []string
	vals := make(map[string][]string)
	for k, vv := range signedHeaders {
		headers = append(headers, strings.ToLower(k))
		vals[strings.ToLower(k)] = vv
	}
	headers = append(headers, "host")
	sort.Strings(headers)

	var buf bytes.Buffer
	for _, k := range headers {
		buf.WriteString(k)
		buf.WriteByte(':')
		switch {
		case k == "host":
			buf.WriteString(r.Request.Host)
			fallthrough
		default:
			for idx, v := range vals[k] {
				if idx > 0 {
					buf.WriteByte(',')
				}
				buf.WriteString(v)
			}
			buf.WriteByte('\n')
		}
	}
	return buf.String()
}
Пример #18
0
// Build a slice of iptables args that are common to from-container and from-host portal rules.
func iptablesCommonPortalArgs(destIP net.IP, addPhysicalInterfaceMatch bool, addDstLocalMatch bool, destPort int, protocol api.Protocol, service proxy.ServicePortName) []string {
	// This list needs to include all fields as they are eventually spit out
	// by iptables-save.  This is because some systems do not support the
	// 'iptables -C' arg, and so fall back on parsing iptables-save output.
	// If this does not match, it will not pass the check.  For example:
	// adding the /32 on the destination IP arg is not strictly required,
	// but causes this list to not match the final iptables-save output.
	// This is fragile and I hope one day we can stop supporting such old
	// iptables versions.
	args := []string{
		"-m", "comment",
		"--comment", service.String(),
		"-p", strings.ToLower(string(protocol)),
		"-m", strings.ToLower(string(protocol)),
		"--dport", fmt.Sprintf("%d", destPort),
	}

	if destIP != nil {
		args = append(args, "-d", fmt.Sprintf("%s/32", destIP.String()))
	}

	if addPhysicalInterfaceMatch {
		args = append(args, "-m", "physdev", "!", "--physdev-is-in")
	}

	if addDstLocalMatch {
		args = append(args, "-m", "addrtype", "--dst-type", "LOCAL")
	}

	return args
}
func (s sortable) Less(i, j int) bool {
	a, b := s[i], s[j]
	if len(a) != len(b) {
		return len(a) > len(b)
	}
	return strings.ToLower(a) < strings.ToLower(b)
}
Пример #20
0
func (e *Evaluator) funcConvert(f *ast.FuncConvertExpr) bool {
	value := f.Expr.GetValue()

	// Casting nil to any type returns nil
	if value == nil {
		f.SetValue(nil)
		return true
	}
	str, ok := value.(string)
	if !ok {
		return true
	}
	if strings.ToLower(f.Charset) == "ascii" {
		f.SetValue(value)
		return true
	} else if strings.ToLower(f.Charset) == "utf8mb4" {
		f.SetValue(value)
		return true
	}

	encoding, _ := charset.Lookup(f.Charset)
	if encoding == nil {
		e.err = ErrInvalidOperation.Gen("unknown encoding: %s", f.Charset)
		return false
	}

	target, _, err := transform.String(encoding.NewDecoder(), str)
	if err != nil {
		log.Errorf("Convert %s to %s with error: %v", str, f.Charset, err)
		e.err = errors.Trace(err)
		return false
	}
	f.SetValue(target)
	return true
}
Пример #21
0
// expapi returns the resources and codec for the experimental api
func (m *Master) expapi(c *Config) *apiserver.APIGroupVersion {

	controllerStorage := expcontrolleretcd.NewStorage(c.DatabaseStorage)
	storage := map[string]rest.Storage{
		strings.ToLower("replicationControllers"):        controllerStorage.ReplicationController,
		strings.ToLower("replicationControllers/scaler"): controllerStorage.Scale,
	}

	return &apiserver.APIGroupVersion{
		Root: m.expAPIPrefix,

		Creater:   api.Scheme,
		Convertor: api.Scheme,
		Typer:     api.Scheme,

		Mapper:  explatest.RESTMapper,
		Codec:   explatest.Codec,
		Linker:  explatest.SelfLinker,
		Storage: storage,
		Version: explatest.Version,

		Admit:   m.admissionControl,
		Context: m.requestContextMapper,

		ProxyDialerFn:     m.dialer,
		MinRequestTimeout: m.minRequestTimeout,
	}
}
Пример #22
0
// ExecuteEntityIds excutes a non-streaming query based on given KeyspaceId map.
func (vtg *VTGate) ExecuteEntityIds(ctx context.Context, sql string, bindVariables map[string]interface{}, keyspace string, entityColumnName string, entityKeyspaceIDs []*pbg.ExecuteEntityIdsRequest_EntityId, tabletType pb.TabletType, session *proto.Session, notInTransaction bool, reply *proto.QueryResult) error {
	startTime := time.Now()
	statsKey := []string{"ExecuteEntityIds", keyspace, strings.ToLower(tabletType.String())}
	defer vtg.timings.Record(statsKey, startTime)

	x := vtg.inFlight.Add(1)
	defer vtg.inFlight.Add(-1)
	if 0 < vtg.maxInFlight && vtg.maxInFlight < x {
		return errTooManyInFlight
	}

	qr, err := vtg.resolver.ExecuteEntityIds(ctx, sql, bindVariables, keyspace, entityColumnName, entityKeyspaceIDs, tabletType, session, notInTransaction)
	if err == nil {
		reply.Result = qr
		vtg.rowsReturned.Add(statsKey, int64(len(qr.Rows)))
	} else {
		query := map[string]interface{}{
			"Sql":               sql,
			"BindVariables":     bindVariables,
			"Keyspace":          keyspace,
			"EntityColumnName":  entityColumnName,
			"EntityKeyspaceIDs": entityKeyspaceIDs,
			"TabletType":        strings.ToLower(tabletType.String()),
			"Session":           session,
			"NotInTransaction":  notInTransaction,
		}
		reply.Error = handleExecuteError(err, statsKey, query, vtg.logExecuteEntityIds).Error()
		reply.Err = rpcErrFromVtGateError(err)
	}
	reply.Session = session
	return nil
}
Пример #23
0
func (slct *Select) FilterItems(search string) {
	bs := slct.theme.BorderSize
	pad := slct.theme.Padding
	inpHeight := slct.input.Geom.Height()
	needle := strings.ToLower(search)

	slct.items = make([]*SelectItem, 0)

	x, y := bs+pad, (2*bs)+pad+inpHeight
	for _, group := range slct.groups {
		shown := false // true when at least 1 item is showing

		if group.hasGroup() {
			group.show(x, y)
			y += group.win.Geom.Height()
		}
		for _, item := range group.items {
			haystack := strings.ToLower(item.text)
			switch slct.tabComplete {
			case TabCompleteAny:
				if !strings.Contains(haystack, needle) {
					item.hide()
					continue
				}
			case TabCompleteMultiple:
				words := strings.Fields(needle)
				match := true
				for _, word := range words {
					if !strings.Contains(haystack, word) {
						match = false
						break
					}
				}
				if !match {
					item.hide()
					continue
				}
			default:
				if !strings.HasPrefix(haystack, needle) {
					item.hide()
					continue
				}
			}

			y += itemTopSpace
			item.show(x, y)
			y += item.regular.Geom.Height() + itemBotSpace
			slct.items = append(slct.items, item)
			shown = true
		}
		if group.hasGroup() {
			if shown {
				y += slct.theme.GroupSpacing
			} else {
				group.hide()
				y -= group.win.Geom.Height()
			}
		}
	}
}
Пример #24
0
func updateUser(e Engine, u *User) error {
	// Organization does not need email
	if !u.IsOrganization() {
		u.Email = strings.ToLower(u.Email)
		has, err := e.Where("id!=?", u.Id).And("type=?", u.Type).And("email=?", u.Email).Get(new(User))
		if err != nil {
			return err
		} else if has {
			return ErrEmailAlreadyUsed{u.Email}
		}

		if len(u.AvatarEmail) == 0 {
			u.AvatarEmail = u.Email
		}
		u.Avatar = base.HashEmail(u.AvatarEmail)
	}

	u.LowerName = strings.ToLower(u.Name)
	u.Location = base.TruncateString(u.Location, 255)
	u.Website = base.TruncateString(u.Website, 255)
	u.Description = base.TruncateString(u.Description, 255)

	u.FullName = markdown.Sanitizer.Sanitize(u.FullName)
	_, err := e.Id(u.Id).AllCols().Update(u)
	return err
}
Пример #25
0
func isTeamCreationAllowed(c *Context, email string) bool {

	email = strings.ToLower(email)

	if !utils.Cfg.TeamSettings.EnableTeamCreation && !HasPermissionToContext(c, model.PERMISSION_MANAGE_SYSTEM) {
		c.Err = model.NewLocAppError("isTeamCreationAllowed", "api.team.is_team_creation_allowed.disabled.app_error", nil, "")
		return false
	}

	if result := <-Srv.Store.User().GetByEmail(email); result.Err == nil {
		user := result.Data.(*model.User)
		if len(user.AuthService) > 0 && len(*user.AuthData) > 0 {
			return true
		}
	}

	// commas and @ signs are optional
	// can be in the form of "@corp.mattermost.com, mattermost.com mattermost.org" -> corp.mattermost.com mattermost.com mattermost.org
	domains := strings.Fields(strings.TrimSpace(strings.ToLower(strings.Replace(strings.Replace(utils.Cfg.TeamSettings.RestrictCreationToDomains, "@", " ", -1), ",", " ", -1))))

	matched := false
	for _, d := range domains {
		if strings.HasSuffix(email, "@"+d) {
			matched = true
			break
		}
	}

	if len(utils.Cfg.TeamSettings.RestrictCreationToDomains) > 0 && !matched {
		c.Err = model.NewLocAppError("isTeamCreationAllowed", "api.team.is_team_creation_allowed.domain.app_error", nil, "")
		return false
	}

	return true
}
Пример #26
0
func TestSignRequestBody(t *testing.T) {
	ac, err := makeAuthConfig()
	if err != nil {
		t.Fatal(err)
	}
	setup()
	defer teardown()

	// Gave up trying to implement this myself
	// nopCloser came from https://groups.google.com/d/msg/golang-nuts/J-Y4LtdGNSw/wDSYbHWIKj0J
	// yay for sharing
	requestBody := strings.NewReader("somecoolbodytext")
	request, err := client.NewRequest("GET", requestURL, requestBody)

	err = ac.SignRequest(request)
	if err != nil {
		t.Fatal("failed to generate RequestHeaders")
	}
	count := 0
	for _, requiredHeader := range testRequiredHeaders {
		for header := range request.Header {
			if strings.ToLower(requiredHeader) == strings.ToLower(header) {
				count++
				break
			}
		}
	}
	if count != len(testRequiredHeaders) {
		t.Error("apiRequestHeaders didn't return all of testRequiredHeaders")
	}
}
Пример #27
0
func describeDeploymentStatus(deploy *kapi.ReplicationController, first, test bool) string {
	timeAt := strings.ToLower(formatRelativeTime(deploy.CreationTimestamp.Time))
	status := deployutil.DeploymentStatusFor(deploy)
	version := deployutil.DeploymentVersionFor(deploy)
	maybeCancelling := ""
	if deployutil.IsDeploymentCancelled(deploy) && !deployutil.IsTerminatedDeployment(deploy) {
		maybeCancelling = " (cancelling)"
	}

	switch status {
	case deployapi.DeploymentStatusFailed:
		reason := deployutil.DeploymentStatusReasonFor(deploy)
		if len(reason) > 0 {
			reason = fmt.Sprintf(": %s", reason)
		}
		// TODO: encode fail time in the rc
		return fmt.Sprintf("deployment #%d failed %s ago%s%s", version, timeAt, reason, describePodSummaryInline(deploy, false))
	case deployapi.DeploymentStatusComplete:
		// TODO: pod status output
		if test {
			return fmt.Sprintf("test deployment #%d deployed %s ago", version, timeAt)
		}
		return fmt.Sprintf("deployment #%d deployed %s ago%s", version, timeAt, describePodSummaryInline(deploy, first))
	case deployapi.DeploymentStatusRunning:
		format := "deployment #%d running%s for %s%s"
		if test {
			format = "test deployment #%d running%s for %s%s"
		}
		return fmt.Sprintf(format, version, maybeCancelling, timeAt, describePodSummaryInline(deploy, false))
	default:
		return fmt.Sprintf("deployment #%d %s%s %s ago%s", version, strings.ToLower(string(status)), maybeCancelling, timeAt, describePodSummaryInline(deploy, false))
	}
}
Пример #28
0
// Execute DML statements in bootstrap stage.
// All the statements run in a single transaction.
func doDMLWorks(s Session) {
	mustExecute(s, "BEGIN")
	// Insert a default user with empty password.
	mustExecute(s, `INSERT INTO mysql.user VALUES
		("localhost", "root", "", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y"),
		("127.0.0.1", "root", "", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y"), 
		("::1", "root", "", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y");`)
	// Init global system variable table.
	values := make([]string, 0, len(variable.SysVars))
	for k, v := range variable.SysVars {
		value := fmt.Sprintf(`("%s", "%s")`, strings.ToLower(k), v.Value)
		values = append(values, value)
	}
	sql := fmt.Sprintf("INSERT INTO %s.%s VALUES %s;", mysql.SystemDB, mysql.GlobalVariablesTable,
		strings.Join(values, ", "))
	mustExecute(s, sql)
	// Init global status variable table.
	values = make([]string, 0, len(variable.StatusVars))
	for k, v := range variable.StatusVars {
		value := fmt.Sprintf(`("%s", "%s")`, strings.ToLower(k), v.Value)
		values = append(values, value)
	}
	sql = fmt.Sprintf("INSERT INTO %s.%s VALUES %s;", mysql.SystemDB, mysql.GlobalStatusTable,
		strings.Join(values, ", "))
	mustExecute(s, sql)
	sql = fmt.Sprintf(`INSERT INTO %s.%s VALUES("%s", "%s", "Bootstrap flag. Do not delete.")
		ON DUPLICATE KEY UPDATE VARIABLE_VALUE="%s"`,
		mysql.SystemDB, mysql.TiDBTable, bootstrappedVar, bootstrappedVarTrue, bootstrappedVarTrue)
	mustExecute(s, sql)
	mustExecute(s, "COMMIT")
}
Пример #29
0
func (d *Driver) getIPByMacFromSettings(mac string) (string, error) {
	network, err := d.conn.LookupNetworkByName(d.PrivateNetwork)
	if err != nil {
		log.Warnf("Failed to find network: %s", err)
		return "", err
	}
	bridge_name, err := network.GetBridgeName()
	if err != nil {
		log.Warnf("Failed to get network bridge: %s", err)
		return "", err
	}
	statusFile := fmt.Sprintf(dnsmasqStatus, bridge_name)
	data, err := ioutil.ReadFile(statusFile)
	type Lease struct {
		Ip_address  string `json:"ip-address"`
		Mac_address string `json:"mac-address"`
		// Other unused fields omitted
	}
	var s []Lease

	err = json.Unmarshal(data, &s)
	if err != nil {
		log.Warnf("Failed to decode dnsmasq lease status: %s", err)
		return "", err
	}
	for _, value := range s {
		if strings.ToLower(value.Mac_address) == strings.ToLower(mac) {
			log.Debugf("IP address: %s", value.Ip_address)
			return value.Ip_address, nil
		}
	}
	return "", nil
}
Пример #30
0
//get the execute database for set sql
func (c *ClientConn) getSetExecDB(tokens []string, tokensLen int, sql string) (*ExecuteDB, error) {
	executeDB := new(ExecuteDB)

	//handle three styles:
	//set autocommit= 0
	//set autocommit = 0
	//set autocommit=0
	if 2 <= len(tokens) {
		before := strings.Split(sql, "=")
		//uncleanWorld is 'autocommit' or 'autocommit '
		uncleanWord := strings.Split(before[0], " ")
		secondWord := strings.ToLower(uncleanWord[1])
		if _, ok := mysql.SET_KEY_WORDS[secondWord]; ok {
			return nil, nil
		}

		//SET [gobal/session] TRANSACTION ISOLATION LEVEL SERIALIZABLE
		//ignore this sql
		if 3 <= len(uncleanWord) {
			if strings.ToLower(uncleanWord[1]) == mysql.TK_STR_TRANSACTION ||
				strings.ToLower(uncleanWord[2]) == mysql.TK_STR_TRANSACTION {
				return nil, errors.ErrIgnoreSQL
			}
		}
	}

	err := c.setExecuteNode(tokens, tokensLen, executeDB)
	if err != nil {
		return nil, err
	}

	return executeDB, nil
}