github.com/makyo/juju@v0.0.0-20160425123129-2608902037e9/apiserver/block/client.go (about) 1 // Copyright 2015 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package block 5 6 import ( 7 "github.com/juju/errors" 8 9 "github.com/juju/juju/apiserver/common" 10 "github.com/juju/juju/apiserver/params" 11 "github.com/juju/juju/state" 12 ) 13 14 func init() { 15 common.RegisterStandardFacade("Block", 2, NewAPI) 16 } 17 18 // Block defines the methods on the block API end point. 19 type Block interface { 20 // List returns all current blocks for this environment. 21 List() (params.BlockResults, error) 22 23 // SwitchBlockOn switches desired block type on for this 24 // environment. 25 SwitchBlockOn(params.BlockSwitchParams) params.ErrorResult 26 27 // SwitchBlockOff switches desired block type off for this 28 // environment. 29 SwitchBlockOff(params.BlockSwitchParams) params.ErrorResult 30 } 31 32 // API implements Block interface and is the concrete 33 // implementation of the api end point. 34 type API struct { 35 access blockAccess 36 authorizer common.Authorizer 37 } 38 39 // NewAPI returns a new block API facade. 40 func NewAPI( 41 st *state.State, 42 resources *common.Resources, 43 authorizer common.Authorizer, 44 ) (*API, error) { 45 if !authorizer.AuthClient() { 46 return nil, common.ErrPerm 47 } 48 49 return &API{ 50 access: getState(st), 51 authorizer: authorizer, 52 }, nil 53 } 54 55 var getState = func(st *state.State) blockAccess { 56 return stateShim{st} 57 } 58 59 // List implements Block.List(). 60 func (a *API) List() (params.BlockResults, error) { 61 all, err := a.access.AllBlocks() 62 if err != nil { 63 return params.BlockResults{}, common.ServerError(err) 64 } 65 found := make([]params.BlockResult, len(all)) 66 for i, one := range all { 67 found[i] = convertBlock(one) 68 } 69 return params.BlockResults{Results: found}, nil 70 } 71 72 func convertBlock(b state.Block) params.BlockResult { 73 result := params.BlockResult{} 74 tag, err := b.Tag() 75 if err != nil { 76 err := errors.Annotatef(err, "getting block %v", b.Type().String()) 77 result.Error = common.ServerError(err) 78 } 79 result.Result = params.Block{ 80 Id: b.Id(), 81 Tag: tag.String(), 82 Type: b.Type().String(), 83 Message: b.Message(), 84 } 85 return result 86 } 87 88 // SwitchBlockOn implements Block.SwitchBlockOn(). 89 func (a *API) SwitchBlockOn(args params.BlockSwitchParams) params.ErrorResult { 90 err := a.access.SwitchBlockOn(state.ParseBlockType(args.Type), args.Message) 91 return params.ErrorResult{Error: common.ServerError(err)} 92 } 93 94 // SwitchBlockOff implements Block.SwitchBlockOff(). 95 func (a *API) SwitchBlockOff(args params.BlockSwitchParams) params.ErrorResult { 96 err := a.access.SwitchBlockOff(state.ParseBlockType(args.Type)) 97 return params.ErrorResult{Error: common.ServerError(err)} 98 }