本文整理汇总了Golang中github.com/snapcore/snapd/overlord/state.Lock函数的典型用法代码示例。如果您正苦于以下问题:Golang Lock函数的具体用法?Golang Lock怎么用?Golang Lock使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Lock函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestNewWithPatches
func (ovs *overlordSuite) TestNewWithPatches(c *C) {
p := func(s *state.State) error {
s.Set("patched", true)
return nil
}
patch.Mock(1, map[int]func(*state.State) error{1: p})
fakeState := []byte(fmt.Sprintf(`{"data":{"patch-level":0}}`))
err := ioutil.WriteFile(dirs.SnapStateFile, fakeState, 0600)
c.Assert(err, IsNil)
o, err := overlord.New()
c.Assert(err, IsNil)
state := o.State()
c.Assert(err, IsNil)
state.Lock()
defer state.Unlock()
var level int
err = state.Get("patch-level", &level)
c.Assert(err, IsNil)
c.Check(level, Equals, 1)
var b bool
err = state.Get("patched", &b)
c.Assert(err, IsNil)
c.Check(b, Equals, true)
}
示例2: TestAddHandlerGenerator
func (s *repositorySuite) TestAddHandlerGenerator(c *C) {
repository := newRepository()
var calledContext *Context
mockHandlerGenerator := func(context *Context) Handler {
calledContext = context
return hooktest.NewMockHandler()
}
// Verify that a handler generator can be added to the repository
repository.addHandlerGenerator(regexp.MustCompile("test-hook"), mockHandlerGenerator)
state := state.New(nil)
state.Lock()
task := state.NewTask("test-task", "my test task")
setup := &HookSetup{Snap: "test-snap", Revision: snap.R(1), Hook: "test-hook"}
context := &Context{task: task, setup: setup}
state.Unlock()
c.Assert(context, NotNil)
// Verify that the handler can be generated
handlers := repository.generateHandlers(context)
c.Check(handlers, HasLen, 1)
c.Check(calledContext, DeepEquals, context)
// Add another handler
repository.addHandlerGenerator(regexp.MustCompile(".*-hook"), mockHandlerGenerator)
// Verify that two handlers are generated for the test-hook, now
handlers = repository.generateHandlers(context)
c.Check(handlers, HasLen, 2)
c.Check(calledContext, DeepEquals, context)
}
示例3: assertsFindMany
func assertsFindMany(c *Command, r *http.Request, user *auth.UserState) Response {
assertTypeName := muxVars(r)["assertType"]
assertType := asserts.Type(assertTypeName)
if assertType == nil {
return BadRequest("invalid assert type: %q", assertTypeName)
}
headers := map[string]string{}
q := r.URL.Query()
for k := range q {
headers[k] = q.Get(k)
}
state := c.d.overlord.State()
state.Lock()
db := assertstate.DB(state)
state.Unlock()
assertions, err := db.FindMany(assertType, headers)
if err == asserts.ErrNotFound {
return AssertResponse(nil, true)
} else if err != nil {
return InternalError("searching assertions failed: %v", err)
}
return AssertResponse(assertions, true)
}
示例4: abortChange
func abortChange(c *Command, r *http.Request, user *auth.UserState) Response {
chID := muxVars(r)["id"]
state := c.d.overlord.State()
state.Lock()
defer state.Unlock()
chg := state.Change(chID)
if chg == nil {
return NotFound("cannot find change with id %q", chID)
}
var reqData struct {
Action string `json:"action"`
}
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&reqData); err != nil {
return BadRequest("cannot decode data from request body: %v", err)
}
if reqData.Action != "abort" {
return BadRequest("change action %q is unsupported", reqData.Action)
}
if chg.Status().Ready() {
return BadRequest("cannot abort change %s with nothing pending", chID)
}
// flag the change
chg.Abort()
// actually ask to proceed with the abort
ensureStateSoon(state)
return SyncResponse(change2changeInfo(chg), nil)
}
示例5: TestGetTests
func (s *getSuite) TestGetTests(c *C) {
for _, test := range getTests {
c.Logf("Test: %s", test.args)
mockHandler := hooktest.NewMockHandler()
state := state.New(nil)
state.Lock()
task := state.NewTask("test-task", "my test task")
setup := &hookstate.HookSetup{Snap: "test-snap", Revision: snap.R(1), Hook: "test-hook"}
var err error
mockContext, err := hookstate.NewContext(task, setup, mockHandler)
c.Check(err, IsNil)
// Initialize configuration
t := configstate.NewTransaction(state)
t.Set("test-snap", "test-key1", "test-value1")
t.Set("test-snap", "test-key2", 2)
t.Commit()
state.Unlock()
stdout, stderr, err := ctlcmd.Run(mockContext, strings.Fields(test.args))
if test.error != "" {
c.Check(err, ErrorMatches, test.error)
} else {
c.Check(err, IsNil)
c.Check(string(stderr), Equals, "")
c.Check(string(stdout), Equals, test.stdout)
}
}
}
示例6: ServeHTTP
func (c *Command) ServeHTTP(w http.ResponseWriter, r *http.Request) {
state := c.d.overlord.State()
state.Lock()
// TODO Look at the error and fail if there's an attempt to authenticate with invalid data.
user, _ := UserFromRequest(state, r)
state.Unlock()
if !c.canAccess(r, user) {
Unauthorized("access denied").ServeHTTP(w, r)
return
}
var rspf ResponseFunc
var rsp = BadMethod("method %q not allowed", r.Method)
switch r.Method {
case "GET":
rspf = c.GET
case "PUT":
rspf = c.PUT
case "POST":
rspf = c.POST
case "DELETE":
rspf = c.DELETE
}
if rspf != nil {
rsp = rspf(c, r, user)
}
rsp.ServeHTTP(w, r)
}
示例7: SetUpTest
func (s *contextSuite) SetUpTest(c *C) {
state := state.New(nil)
state.Lock()
defer state.Unlock()
s.task = state.NewTask("test-task", "my test task")
s.setup = &HookSetup{Snap: "test-snap", Revision: snap.R(1), Hook: "test-hook"}
var err error
s.context, err = NewContext(s.task, s.setup, nil)
c.Check(err, IsNil)
}
示例8: getChanges
func getChanges(c *Command, r *http.Request, user *auth.UserState) Response {
query := r.URL.Query()
qselect := query.Get("select")
if qselect == "" {
qselect = "in-progress"
}
var filter func(*state.Change) bool
switch qselect {
case "all":
filter = func(*state.Change) bool { return true }
case "in-progress":
filter = func(chg *state.Change) bool { return !chg.Status().Ready() }
case "ready":
filter = func(chg *state.Change) bool { return chg.Status().Ready() }
default:
return BadRequest("select should be one of: all,in-progress,ready")
}
if wantedName := query.Get("for"); wantedName != "" {
outerFilter := filter
filter = func(chg *state.Change) bool {
if !outerFilter(chg) {
return false
}
var snapNames []string
if err := chg.Get("snap-names", &snapNames); err != nil {
logger.Noticef("Cannot get snap-name for change %v", chg.ID())
return false
}
for _, snapName := range snapNames {
if snapName == wantedName {
return true
}
}
return false
}
}
state := c.d.overlord.State()
state.Lock()
defer state.Unlock()
chgs := state.Changes()
chgInfos := make([]*changeInfo, 0, len(chgs))
for _, chg := range chgs {
if !filter(chg) {
continue
}
chgInfos = append(chgInfos, change2changeInfo(chg))
}
return SyncResponse(chgInfos, nil)
}
示例9: getChange
func getChange(c *Command, r *http.Request, user *auth.UserState) Response {
chID := muxVars(r)["id"]
state := c.d.overlord.State()
state.Lock()
defer state.Unlock()
chg := state.Change(chID)
if chg == nil {
return NotFound("cannot find change with id %q", chID)
}
return SyncResponse(change2changeInfo(chg), nil)
}
示例10: SetUpTest
func (s *setSuite) SetUpTest(c *C) {
s.mockHandler = hooktest.NewMockHandler()
state := state.New(nil)
state.Lock()
defer state.Unlock()
task := state.NewTask("test-task", "my test task")
setup := &hookstate.HookSetup{Snap: "test-snap", Revision: snap.R(1), Hook: "test-hook"}
var err error
s.mockContext, err = hookstate.NewContext(task, setup, s.mockHandler)
c.Assert(err, IsNil)
}
示例11: changeInterfaces
// changeInterfaces controls the interfaces system.
// Plugs can be connected to and disconnected from slots.
// When enableInternalInterfaceActions is true plugs and slots can also be
// explicitly added and removed.
func changeInterfaces(c *Command, r *http.Request, user *auth.UserState) Response {
var a interfaceAction
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&a); err != nil {
return BadRequest("cannot decode request body into an interface action: %v", err)
}
if a.Action == "" {
return BadRequest("interface action not specified")
}
if !c.d.enableInternalInterfaceActions && a.Action != "connect" && a.Action != "disconnect" {
return BadRequest("internal interface actions are disabled")
}
if len(a.Plugs) > 1 || len(a.Slots) > 1 {
return NotImplemented("many-to-many operations are not implemented")
}
if a.Action != "connect" && a.Action != "disconnect" {
return BadRequest("unsupported interface action: %q", a.Action)
}
if len(a.Plugs) == 0 || len(a.Slots) == 0 {
return BadRequest("at least one plug and slot is required")
}
var summary string
var taskset *state.TaskSet
var err error
state := c.d.overlord.State()
state.Lock()
defer state.Unlock()
switch a.Action {
case "connect":
summary = fmt.Sprintf("Connect %s:%s to %s:%s", a.Plugs[0].Snap, a.Plugs[0].Name, a.Slots[0].Snap, a.Slots[0].Name)
taskset, err = ifacestate.Connect(state, a.Plugs[0].Snap, a.Plugs[0].Name, a.Slots[0].Snap, a.Slots[0].Name)
case "disconnect":
summary = fmt.Sprintf("Disconnect %s:%s from %s:%s", a.Plugs[0].Snap, a.Plugs[0].Name, a.Slots[0].Snap, a.Slots[0].Name)
taskset, err = ifacestate.Disconnect(state, a.Plugs[0].Snap, a.Plugs[0].Name, a.Slots[0].Snap, a.Slots[0].Name)
}
if err != nil {
return BadRequest("%v", err)
}
change := state.NewChange(a.Action+"-snap", summary)
change.Set("snap-names", []string{a.Plugs[0].Snap, a.Slots[0].Snap})
change.AddAll(taskset)
state.EnsureBefore(0)
return AsyncResponse(nil, &Meta{Change: change.ID()})
}
示例12: logoutUser
func logoutUser(c *Command, r *http.Request, user *auth.UserState) Response {
state := c.d.overlord.State()
state.Lock()
defer state.Unlock()
if user == nil {
return BadRequest("not logged in")
}
err := auth.RemoveUser(state, user.ID)
if err != nil {
return InternalError(err.Error())
}
return SyncResponse(nil, nil)
}
示例13: storeUpdates
func storeUpdates(c *Command, r *http.Request, user *auth.UserState) Response {
route := c.d.router.Get(snapCmd.Path)
if route == nil {
return InternalError("cannot find route for snaps")
}
state := c.d.overlord.State()
state.Lock()
updates, err := snapstateRefreshCandidates(state, user)
state.Unlock()
if err != nil {
return InternalError("cannot list updates: %v", err)
}
return sendStorePackages(route, nil, updates)
}
示例14: SetUpTest
func (s *getSuite) SetUpTest(c *C) {
s.mockHandler = hooktest.NewMockHandler()
state := state.New(nil)
state.Lock()
defer state.Unlock()
task := state.NewTask("test-task", "my test task")
setup := &hookstate.HookSetup{Snap: "test-snap", Revision: snap.R(1), Hook: "test-hook"}
var err error
s.mockContext, err = hookstate.NewContext(task, setup, s.mockHandler)
c.Assert(err, IsNil)
// Initialize configuration
transaction := configstate.NewTransaction(state)
transaction.Set("test-snap", "initial-key", "initial-value")
transaction.Commit()
}
示例15: doAssert
func doAssert(c *Command, r *http.Request, user *auth.UserState) Response {
batch := assertstate.NewBatch()
_, err := batch.AddStream(r.Body)
if err != nil {
return BadRequest("cannot decode request body into assertions: %v", err)
}
state := c.d.overlord.State()
state.Lock()
defer state.Unlock()
if err := batch.Commit(state); err != nil {
return BadRequest("assert failed: %v", err)
}
// TODO: what more info do we want to return on success?
return &resp{
Type: ResponseTypeSync,
Status: http.StatusOK,
}
}