// FindSession attempts to find a debug hooks session for the unit specified
// in the context, and returns a new ServerSession structure for it.
4583
func (c *HooksContext) FindSession() (*ServerSession, error) {
	cmd := exec.Command("tmux", "has-session", "-t", c.tmuxSessionName())
	out, err := cmd.CombinedOutput()
	if err != nil {
		if len(out) != 0 {
			return nil, errors.New(string(out))
		} else {
			return nil, err
		}
	}
	// Parse the debug-hooks file for an optional hook name.
	data, err := ioutil.ReadFile(c.ClientFileLock())
	if err != nil {
		return nil, err
	}
	var args hookArgs
	err = goyaml.Unmarshal(data, &args)
	if err != nil {
		return nil, err
	}
	hooks := set.NewStrings(args.Hooks...)
	session := &ServerSession{HooksContext: c, hooks: hooks}
	return session, nil
}
1295119
func (c *Client) UpdateSession(req session.UpdateRequest) error {
	if err := req.Check(); err != nil {
		return trace.Wrap(err)
	}
	_, err := c.PutJSON(c.Endpoint("namespaces", req.Namespace, "sessions", string(req.ID)), updateSessionReq{Update: req})
	return trace.Wrap(err)
}
386646
func (s *server) GetSessions(namespace string) ([]Session, error) {
	prefix := activePrefix(namespace)

	result, err := s.bk.GetRange(context.TODO(), prefix, backend.RangeEnd(prefix), MaxSessionSliceLength)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	out := make(Sessions, 0, len(result.Items))

	for i := range result.Items {
		var session Session
		if err := json.Unmarshal(result.Items[i].Value, &session); err != nil {
			return nil, trace.Wrap(err)
		}
		out = append(out, session)
	}
	sort.Stable(out)
	return out, nil
}
219744
func (s *server) CreateSession(sess Session) error {
	if err := sess.ID.Check(); err != nil {
		return trace.Wrap(err)
	}
	if sess.Namespace == "" {
		return trace.BadParameter("session namespace can not be empty")
	}
	if sess.Login == "" {
		return trace.BadParameter("session login can not be empty")
	}
	if sess.Created.IsZero() {
		return trace.BadParameter("created can not be empty")
	}
	if sess.LastActive.IsZero() {
		return trace.BadParameter("last_active can not be empty")
	}
	_, err := NewTerminalParamsFromInt(sess.TerminalParams.W, sess.TerminalParams.H)
	if err != nil {
		return trace.Wrap(err)
	}
	sess.Parties = nil
	data, err := json.Marshal(sess)
	if err != nil {
		return trace.Wrap(err)
	}
	item := backend.Item{
		Key:     activeKey(sess.Namespace, string(sess.ID)),
		Value:   data,
		Expires: s.clock.Now().UTC().Add(s.activeSessionTTL),
	}
	_, err = s.bk.Create(context.TODO(), item)
	if err != nil {
		return trace.Wrap(err)
	}
	return nil
}
30975
func (api *CoreAPI) getSession(ctx context.Context) *CoreAPI {
	sesApi := *api

	// TODO: We could also apply this to api.blocks, and compose into writable api,
	// but this requires some changes in blockservice/merkledag
	sesApi.dag = dag.NewReadOnlyDagService(dag.NewSession(ctx, api.dag))

	return &sesApi
}
469403
func NewSession(username, password, organization, url string) (*bambou.Session, *Me) {

	root := NewMe()
	url += urlpostfix

	session := bambou.NewSession(username, password, organization, url, root)

	return session, root
}
514115
func findClosestSessions(session string) []string {
	sessionsTree := trie.NewTrie() // Allocate a new trie for sessions strings.
	for _, sid := range getSessionIDs() {
		sessionsTree.Insert(sid)
	}
	var closestSessions []string
	for _, value := range sessionsTree.PrefixMatch(session) {
		closestSessions = append(closestSessions, value.(string))
	}
	sort.Strings(closestSessions)
	return closestSessions
}
1024625
func NewSessionService() *SessionService {
	return &SessionService{
		FindSessionFn:   func(context.Context, string) (*platform.Session, error) { return nil, fmt.Errorf("mock session") },
		CreateSessionFn: func(context.Context, string) (*platform.Session, error) { return nil, fmt.Errorf("mock session") },
		ExpireSessionFn: func(context.Context, string) error { return fmt.Errorf("mock session") },
	}
}
802103
func (p *Provider) GetSession(token string) (map[string]string, error) {
	sess := struct {
		Name       string `xml:"name"`
		Key        string `xml:"key"`
		Subscriber bool   `xml:"subscriber"`
	}{}

	err := p.request(true, map[string]string{"method": "auth.getSession", "token": token}, &sess)
	return map[string]string{"login": sess.Name, "token": sess.Key}, err
}
177973
func (s *SessionStore) GetSession(c context.Context, sessionID string) (*auth.Session, error) {
	c = defaultNS(c)
	ent, err := s.fetchSession(c, sessionID)
	if ent == nil {
		return nil, err
	}
	return &auth.Session{
		SessionID: sessionID,
		UserID:    ent.Parent.StringID()[len(s.Prefix)+1:],
		User: auth.User{
			Identity:  identity.Identity(ent.Profile.Identity),
			Superuser: ent.Profile.Superuser,
			Email:     ent.Profile.Email,
			Name:      ent.Profile.Name,
			Picture:   ent.Profile.Picture,
		},
		Exp: ent.Expiration,
	}, nil
}
436390
func (r *sessionRepository) FindByToken(ctx context.Context, token string) (*sessions.Session, error) {
	conn := r.pool.Get()
	defer conn.Close()

	return getSession(conn, sessionKey(token))
}
643091
func NewSession(cfg ClusterConfig) (*Session, error) {
	// Check that hosts in the ClusterConfig is not empty
	if len(cfg.Hosts) < 1 {
		return nil, ErrNoHosts
	}

	// Check that either Authenticator is set or AuthProvider, not both
	if cfg.Authenticator != nil && cfg.AuthProvider != nil {
		return nil, errors.New("Can't use both Authenticator and AuthProvider in cluster config.")
	}

	s := &Session{
		cons:            cfg.Consistency,
		prefetch:        0.25,
		cfg:             cfg,
		pageSize:        cfg.PageSize,
		stmtsLRU:        &preparedLRU{lru: lru.New(cfg.MaxPreparedStmts)},
		quit:            make(chan struct{}),
		connectObserver: cfg.ConnectObserver,
	}

	s.schemaDescriber = newSchemaDescriber(s)

	s.nodeEvents = newEventDebouncer("NodeEvents", s.handleNodeEvent)
	s.schemaEvents = newEventDebouncer("SchemaEvents", s.handleSchemaEvent)

	s.routingKeyInfoCache.lru = lru.New(cfg.MaxRoutingKeyInfo)

	s.hostSource = &ringDescriber{session: s}

	if cfg.PoolConfig.HostSelectionPolicy == nil {
		cfg.PoolConfig.HostSelectionPolicy = RoundRobinHostPolicy()
	}
	s.pool = cfg.PoolConfig.buildPool(s)

	s.policy = cfg.PoolConfig.HostSelectionPolicy
	s.policy.Init(s)

	s.executor = &queryExecutor{
		pool:   s.pool,
		policy: cfg.PoolConfig.HostSelectionPolicy,
	}

	s.queryObserver = cfg.QueryObserver
	s.batchObserver = cfg.BatchObserver
	s.connectObserver = cfg.ConnectObserver
	s.frameObserver = cfg.FrameHeaderObserver

	//Check the TLS Config before trying to connect to anything external
	connCfg, err := connConfig(&s.cfg)
	if err != nil {
		//TODO: Return a typed error
		return nil, fmt.Errorf("gocql: unable to create session: %v", err)
	}
	s.connCfg = connCfg

	if err := s.init(); err != nil {
		s.Close()
		if err == ErrNoConnectionsStarted {
			//This error used to be generated inside NewSession & returned directly
			//Forward it on up to be backwards compatible
			return nil, ErrNoConnectionsStarted
		} else {
			// TODO(zariel): dont wrap this error in fmt.Errorf, return a typed error
			return nil, fmt.Errorf("gocql: unable to create session: %v", err)
		}
	}

	return s, nil
}
456355
func (mgr *MemorySessionManager) NewSession() (Session, error) {
	sid, err := mgr.sessionID()
	if err != nil {
		return nil, err
	}
	s := MemorySession{sid: sid, data: make(map[string]interface{}), createdAt: time.Now()}
	mgr.lock.Lock()
	mgr.sessions[sid] = &s
	mgr.lock.Unlock()
	return &s, nil
}
722691
func (c *Connector) GetSessionData(ctx context.Context) (*SessionData, error) {
	s := pitaya.GetSessionFromCtx(ctx)
	res := &SessionData{
		Data: s.GetData(),
	}
	return res, nil
}
1159142
func NewSession(opts ...Option) *Session {
	var s Session
	s.buffers = &sync.Pool{
		New: func() interface{} {
			return make([]byte, 65536)
		},
	}

	for _, opt := range opts {
		opt(&s)
	}

	if s.withIDAliasing {
		s.signatures = make(map[[sha1.Size]byte]uint16)
		s.aliases = make(map[uint16]uint16)
		s.nextID = 256
	}

	s.specifiers = make(map[uint16][]TemplateFieldSpecifier)
	s.minRecord = make(map[uint16]uint16)

	return &s
}
658915
func (s *Service) CreateSession(ctx context.Context, user string) (*platform.Session, error) {
	u, pe := s.findUserByName(ctx, user)
	if pe != nil {
		return nil, &platform.Error{
			Err: pe,
		}
	}

	sess := &platform.Session{}
	sess.ID = s.IDGenerator.ID()
	k, err := s.TokenGenerator.Token()
	if err != nil {
		return nil, &platform.Error{
			Err: err,
		}
	}
	sess.Key = k
	sess.UserID = u.ID
	sess.CreatedAt = time.Now()
	// TODO(desa): make this configurable
	sess.ExpiresAt = sess.CreatedAt.Add(time.Hour)
	// TODO(desa): not totally sure what to do here. Possibly we should have a maximal privilege permission.
	sess.Permissions = []platform.Permission{}

	if err := s.PutSession(ctx, sess); err != nil {
		return nil, err
	}

	return sess, nil
}
769633
func (c *Client) GetSession(namespace string, id session.ID) (*session.Session, error) {
	if namespace == "" {
		return nil, trace.BadParameter(MissingNamespaceError)
	}
	// saving extra round-trip
	if err := id.Check(); err != nil {
		return nil, trace.Wrap(err)
	}
	out, err := c.Get(c.Endpoint("namespaces", namespace, "sessions", string(id)), url.Values{})
	if err != nil {
		return nil, trace.Wrap(err)
	}
	var sess *session.Session
	if err := json.Unmarshal(out.Bytes(), &sess); err != nil {
		return nil, trace.Wrap(err)
	}
	return sess, nil
}