<commit_before>// Copyright 2015 Comcast Cable Communications Management, LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// End Copyright

package sys

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"runtime"
	"runtime/pprof"
	"strings"
	"sync"
	"sync/atomic"
	"time"
	"unsafe"

	. "github.com/Comcast/rulio/core"
	"github.com/Comcast/rulio/cron"
	"github.com/Comcast/rulio/storage/bolt"
	"github.com/Comcast/rulio/storage/cassandra"
	"github.com/Comcast/rulio/storage/dynamodb"
)

// LocToGroup maps a location name to a group name.
//
// Used to be called 'GroupMap'.
type LocToGroup func(string) string

// GroupControls maps a group to a 'core.Control'.
//
// Used to be called 'LocControls'
type GroupControls map[string]*Control

// System is a location container.
//
// A System is responsible for loading locations and directing API
// requests to then.
type System struct {
	sync.Mutex
	cron    cron.Cronner
	storage Storage
	config  SystemConfig
	control unsafe.Pointer // *SystemControl
	stats   ServiceStats
	*CachedLocations
	ProfCPUFile *os.File
}

// CachedLocations is just that: a location cache keyed by name.
//
// We have this struct in part to have a mutex dedicated to this
// state.
type CachedLocations struct {
	sync.Mutex
	locs map[string]*CachedLocation
}

func NewCachedLocations(ctx *Context) *CachedLocations {
	return &CachedLocations{
		sync.Mutex{},
		make(map[string]*CachedLocation),
	}
}

func (cl *CachedLocations) Count() int {
	cl.Lock()
	n := len(cl.locs)
	cl.Unlock()
	return n
}

// expire checks the cache for the given location and determines if
// the cache value has expired.  Either way, returns the location (if
// any).  If the cached location has expired, it is removed from the
// cache.
//
// A cached location is expired if it is not pending and its
// expiration time is before the current time.
//
// Assumes a lock for the CachedLocations.
func (cls *CachedLocations) expire(ctx *Context, sys *System, name string, released bool) (*Location, bool) {
	// Assumes lock
	Log(INFO, ctx, "CachedLocations.expire", "name", name)
	cl, have := cls.locs[name]
	var loc *Location
	dead := false
	if have {
		cl.Pending = !released
		Log(INFO, ctx, "CachedLocations.expire", "name", name, "cached", "exists")
		if cl.Pending || cl.Expires.After(time.Now()) {
			Log(INFO, ctx, "CachedLocations.expire", "name", name, "cached", "live")
			loc = cl.Location
		} else {
			Log(INFO, ctx, "CachedLocations.expire", "name", name, "cached", "expired")
			delete(cls.locs, name)
			cl = nil
		}
	}
	return loc, dead
}

// Open gets a location from the cache after first creating it.
//
// This function the top-level location cache API, and it uses
// 'CachedLocations.Get()' to do the real work.
//
// TTL can be 'Never', 'Forever', or anything in between.
func (cls *CachedLocations) Open(ctx *Context, sys *System, name string, check bool) (*Location, error) {
	Log(INFO, ctx, "CachedLocations.Open", "name", name)
	cls.Lock()

	loc, dead := cls.expire(ctx, sys, name, false)

	var err error
	if loc == nil || dead {
		Log(INFO, ctx, "CachedLocations.Open", "name", name, "cached", "empty")
		ctl := sys.Control()
		ttl := ctl.LocationTTL

		expires := EndOfTime
		if ttl != Forever {
			expires = time.Now().Add(ttl)
		}<commit_msg>Eliminate a race condition during expiration check<commit_after>// Copyright 2015 Comcast Cable Communications Management, LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// End Copyright

package sys

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"runtime"
	"runtime/pprof"
	"strings"
	"sync"
	"sync/atomic"
	"time"
	"unsafe"

	. "github.com/Comcast/rulio/core"
	"github.com/Comcast/rulio/cron"
	"github.com/Comcast/rulio/storage/bolt"
	"github.com/Comcast/rulio/storage/cassandra"
	"github.com/Comcast/rulio/storage/dynamodb"
)

// LocToGroup maps a location name to a group name.
//
// Used to be called 'GroupMap'.
type LocToGroup func(string) string

// GroupControls maps a group to a 'core.Control'.
//
// Used to be called 'LocControls'
type GroupControls map[string]*Control

// System is a location container.
//
// A System is responsible for loading locations and directing API
// requests to then.
type System struct {
	sync.Mutex
	cron    cron.Cronner
	storage Storage
	config  SystemConfig
	control unsafe.Pointer // *SystemControl
	stats   ServiceStats
	*CachedLocations
	ProfCPUFile *os.File
}

// CachedLocations is just that: a location cache keyed by name.
//
// We have this struct in part to have a mutex dedicated to this
// state.
type CachedLocations struct {
	sync.Mutex
	locs map[string]*CachedLocation
}

func NewCachedLocations(ctx *Context) *CachedLocations {
	return &CachedLocations{
		sync.Mutex{},
		make(map[string]*CachedLocation),
	}
}

func (cl *CachedLocations) Count() int {
	cl.Lock()
	n := len(cl.locs)
	cl.Unlock()
	return n
}

// expire checks the cache for the given location and determines if
// the cache value has expired.  Either way, returns the location (if
// any).  If the cached location has expired, it is removed from the
// cache.
//
// A cached location is expired if it is not pending and its
// expiration time is before the current time.
//
// Assumes a lock for the CachedLocations.
func (cls *CachedLocations) expire(ctx *Context, sys *System, name string, released bool) (*Location, bool) {
	// Assumes lock
	Log(INFO, ctx, "CachedLocations.expire", "name", name)
	cl, have := cls.locs[name]
	var loc *Location
	dead := false
	if have {
		cl.Lock()
		cl.Pending = !released
		Log(INFO, ctx, "CachedLocations.expire", "name", name, "cached", "exists")
		if cl.Pending || cl.Expires.After(time.Now()) {
			Log(INFO, ctx, "CachedLocations.expire", "name", name, "cached", "live")
			loc = cl.Location
		} else {
			Log(INFO, ctx, "CachedLocations.expire", "name", name, "cached", "expired")
			delete(cls.locs, name)
		}
		cl.Unlock()
	}
	return loc, dead
}

// Open gets a location from the cache after first creating it.
//
// This function the top-level location cache API, and it uses
// 'CachedLocations.Get()' to do the real work.
//
// TTL can be 'Never', 'Forever', or anything in between.
func (cls *CachedLocations) Open(ctx *Context, sys *System, name string, check bool) (*Location, error) {
	Log(INFO, ctx, "CachedLocations.Open", "name", name)
	cls.Lock()

	loc, dead := cls.expire(ctx, sys, name, false)

	var err error
	if loc == nil || dead {
		Log(INFO, ctx, "CachedLocations.Open", "name", name, "cached", "empty")
		ctl := sys.Control()
		ttl := ctl.LocationTTL

		expires := EndOfTime
		if ttl != Forever {
			expires = time.Now().Add(ttl)
		}
{'fraction_non_alphanumeric': 0.1254377999740563, 'fraction_numerical': 0.0020754961733039303, 'mean_word_length': 3.6698970321017566, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5123637', 'n_tokens_mistral': 2605, 'n_tokens_neox': 2522, 'n_words': 886}