Statistics
| Branch: | Tag: | Revision:

root / src / Ganeti / Config.hs @ da4a52a3

History | View | Annotate | Download (11.6 kB)

1
{-| Implementation of the Ganeti configuration database.
2

    
3
-}
4

    
5
{-
6

    
7
Copyright (C) 2011, 2012 Google Inc.
8

    
9
This program is free software; you can redistribute it and/or modify
10
it under the terms of the GNU General Public License as published by
11
the Free Software Foundation; either version 2 of the License, or
12
(at your option) any later version.
13

    
14
This program is distributed in the hope that it will be useful, but
15
WITHOUT ANY WARRANTY; without even the implied warranty of
16
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17
General Public License for more details.
18

    
19
You should have received a copy of the GNU General Public License
20
along with this program; if not, write to the Free Software
21
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22
02110-1301, USA.
23

    
24
-}
25

    
26
module Ganeti.Config
27
    ( LinkIpMap
28
    , NdParamObject(..)
29
    , loadConfig
30
    , getNodeInstances
31
    , getNodeRole
32
    , getNodeNdParams
33
    , getDefaultNicLink
34
    , getDefaultHypervisor
35
    , getInstancesIpByLink
36
    , getNode
37
    , getInstance
38
    , getGroup
39
    , getGroupNdParams
40
    , getGroupIpolicy
41
    , getGroupDiskParams
42
    , getGroupNodes
43
    , getGroupInstances
44
    , getGroupOfNode
45
    , getInstPrimaryNode
46
    , getInstMinorsForNode
47
    , getNetwork
48
    , buildLinkIpInstnameMap
49
    , instNodes
50
    ) where
51

    
52
import Control.Monad (liftM)
53
import Data.List (foldl')
54
import qualified Data.Map as M
55
import qualified Data.Set as S
56
import qualified Text.JSON as J
57

    
58
import Ganeti.BasicTypes
59
import qualified Ganeti.Constants as C
60
import Ganeti.Errors
61
import Ganeti.JSON
62
import Ganeti.Objects
63
import Ganeti.Types
64

    
65
-- | Type alias for the link and ip map.
66
type LinkIpMap = M.Map String (M.Map String String)
67

    
68
-- | Type class denoting objects which have node parameters.
69
class NdParamObject a where
70
  getNdParamsOf :: ConfigData -> a -> Maybe FilledNDParams
71

    
72
-- | Reads the config file.
73
readConfig :: FilePath -> IO String
74
readConfig = readFile
75

    
76
-- | Parses the configuration file.
77
parseConfig :: String -> Result ConfigData
78
parseConfig = fromJResult "parsing configuration" . J.decodeStrict
79

    
80
-- | Wrapper over 'readConfig' and 'parseConfig'.
81
loadConfig :: FilePath -> IO (Result ConfigData)
82
loadConfig = fmap parseConfig . readConfig
83

    
84
-- * Query functions
85

    
86
-- | Computes the nodes covered by a disk.
87
computeDiskNodes :: Disk -> S.Set String
88
computeDiskNodes dsk =
89
  case diskLogicalId dsk of
90
    LIDDrbd8 nodeA nodeB _ _ _ _ -> S.fromList [nodeA, nodeB]
91
    _ -> S.empty
92

    
93
-- | Computes all disk-related nodes of an instance. For non-DRBD,
94
-- this will be empty, for DRBD it will contain both the primary and
95
-- the secondaries.
96
instDiskNodes :: Instance -> S.Set String
97
instDiskNodes = S.unions . map computeDiskNodes . instDisks
98

    
99
-- | Computes all nodes of an instance.
100
instNodes :: Instance -> S.Set String
101
instNodes inst = instPrimaryNode inst `S.insert` instDiskNodes inst
102

    
103
-- | Computes the secondary nodes of an instance. Since this is valid
104
-- only for DRBD, we call directly 'instDiskNodes', skipping over the
105
-- extra primary insert.
106
instSecondaryNodes :: Instance -> S.Set String
107
instSecondaryNodes inst =
108
  instPrimaryNode inst `S.delete` instDiskNodes inst
109

    
110
-- | Get instances of a given node.
111
getNodeInstances :: ConfigData -> String -> ([Instance], [Instance])
112
getNodeInstances cfg nname =
113
    let all_inst = M.elems . fromContainer . configInstances $ cfg
114
        pri_inst = filter ((== nname) . instPrimaryNode) all_inst
115
        sec_inst = filter ((nname `S.member`) . instSecondaryNodes) all_inst
116
    in (pri_inst, sec_inst)
117

    
118
-- | Computes the role of a node.
119
getNodeRole :: ConfigData -> Node -> NodeRole
120
getNodeRole cfg node
121
  | nodeName node == clusterMasterNode (configCluster cfg) = NRMaster
122
  | nodeMasterCandidate node = NRCandidate
123
  | nodeDrained node = NRDrained
124
  | nodeOffline node = NROffline
125
  | otherwise = NRRegular
126

    
127
-- | Returns the default cluster link.
128
getDefaultNicLink :: ConfigData -> String
129
getDefaultNicLink =
130
  nicpLink . (M.! C.ppDefault) . fromContainer .
131
  clusterNicparams . configCluster
132

    
133
-- | Returns the default cluster hypervisor.
134
getDefaultHypervisor :: ConfigData -> Hypervisor
135
getDefaultHypervisor cfg =
136
  case clusterEnabledHypervisors $ configCluster cfg of
137
    -- FIXME: this case shouldn't happen (configuration broken), but
138
    -- for now we handle it here because we're not authoritative for
139
    -- the config
140
    []  -> XenPvm
141
    x:_ -> x
142

    
143
-- | Returns instances of a given link.
144
getInstancesIpByLink :: LinkIpMap -> String -> [String]
145
getInstancesIpByLink linkipmap link =
146
  M.keys $ M.findWithDefault M.empty link linkipmap
147

    
148
-- | Generic lookup function that converts from a possible abbreviated
149
-- name to a full name.
150
getItem :: String -> String -> M.Map String a -> ErrorResult a
151
getItem kind name allitems = do
152
  let lresult = lookupName (M.keys allitems) name
153
      err msg = Bad $ OpPrereqError (kind ++ " name " ++ name ++ " " ++ msg)
154
                        ECodeNoEnt
155
  fullname <- case lrMatchPriority lresult of
156
                PartialMatch -> Ok $ lrContent lresult
157
                ExactMatch -> Ok $ lrContent lresult
158
                MultipleMatch -> err "has multiple matches"
159
                FailMatch -> err "not found"
160
  maybe (err "not found after successfull match?!") Ok $
161
        M.lookup fullname allitems
162

    
163
-- | Looks up a node by name or uuid.
164
getNode :: ConfigData -> String -> ErrorResult Node
165
getNode cfg name =
166
  let nodes = fromContainer (configNodes cfg)
167
  in case getItem "Node" name nodes of
168
       -- if not found by uuid, we need to look it up by name
169
       Ok node -> Ok node
170
       Bad _ -> let by_name = M.mapKeys
171
                              (nodeName . (M.!) nodes) nodes
172
                in getItem "Node" name by_name
173

    
174
-- | Looks up an instance by name or uuid.
175
getInstance :: ConfigData -> String -> ErrorResult Instance
176
getInstance cfg name =
177
  let instances = fromContainer (configInstances cfg)
178
  in case getItem "Instance" name instances of
179
       -- if not found by uuid, we need to look it up by name
180
       Ok inst -> Ok inst
181
       Bad _ -> let by_name = M.mapKeys
182
                              (instName . (M.!) instances) instances
183
                in getItem "Instance" name by_name
184

    
185
-- | Looks up a node group by name or uuid.
186
getGroup :: ConfigData -> String -> ErrorResult NodeGroup
187
getGroup cfg name =
188
  let groups = fromContainer (configNodegroups cfg)
189
  in case getItem "NodeGroup" name groups of
190
       -- if not found by uuid, we need to look it up by name, slow
191
       Ok grp -> Ok grp
192
       Bad _ -> let by_name = M.mapKeys
193
                              (groupName . (M.!) groups) groups
194
                in getItem "NodeGroup" name by_name
195

    
196
-- | Computes a node group's node params.
197
getGroupNdParams :: ConfigData -> NodeGroup -> FilledNDParams
198
getGroupNdParams cfg ng =
199
  fillNDParams (clusterNdparams $ configCluster cfg) (groupNdparams ng)
200

    
201
-- | Computes a node group's ipolicy.
202
getGroupIpolicy :: ConfigData -> NodeGroup -> FilledIPolicy
203
getGroupIpolicy cfg ng =
204
  fillIPolicy (clusterIpolicy $ configCluster cfg) (groupIpolicy ng)
205

    
206
-- | Computes a group\'s (merged) disk params.
207
getGroupDiskParams :: ConfigData -> NodeGroup -> DiskParams
208
getGroupDiskParams cfg ng =
209
  GenericContainer $
210
  fillDict (fromContainer . clusterDiskparams $ configCluster cfg)
211
           (fromContainer $ groupDiskparams ng) []
212

    
213
-- | Get nodes of a given node group.
214
getGroupNodes :: ConfigData -> String -> [Node]
215
getGroupNodes cfg gname =
216
  let all_nodes = M.elems . fromContainer . configNodes $ cfg in
217
  filter ((==gname) . nodeGroup) all_nodes
218

    
219
-- | Get (primary, secondary) instances of a given node group.
220
getGroupInstances :: ConfigData -> String -> ([Instance], [Instance])
221
getGroupInstances cfg gname =
222
  let gnodes = map nodeUuid (getGroupNodes cfg gname)
223
      ginsts = map (getNodeInstances cfg) gnodes in
224
  (concatMap fst ginsts, concatMap snd ginsts)
225

    
226
-- | Looks up a network. If looking up by uuid fails, we look up
227
-- by name.
228
getNetwork :: ConfigData -> String -> ErrorResult Network
229
getNetwork cfg name =
230
  let networks = fromContainer (configNetworks cfg)
231
  in case getItem "Network" name networks of
232
       Ok net -> Ok net
233
       Bad _ -> let by_name = M.mapKeys
234
                              (fromNonEmpty . networkName . (M.!) networks)
235
                              networks
236
                in getItem "Network" name by_name
237

    
238
-- | Looks up an instance's primary node.
239
getInstPrimaryNode :: ConfigData -> String -> ErrorResult Node
240
getInstPrimaryNode cfg name =
241
  liftM instPrimaryNode (getInstance cfg name) >>= getNode cfg
242

    
243
-- | Filters DRBD minors for a given node.
244
getDrbdMinorsForNode :: String -> Disk -> [(Int, String)]
245
getDrbdMinorsForNode node disk =
246
  let child_minors = concatMap (getDrbdMinorsForNode node) (diskChildren disk)
247
      this_minors =
248
        case diskLogicalId disk of
249
          LIDDrbd8 nodeA nodeB _ minorA minorB _
250
            | nodeA == node -> [(minorA, nodeB)]
251
            | nodeB == node -> [(minorB, nodeA)]
252
          _ -> []
253
  in this_minors ++ child_minors
254

    
255
-- | String for primary role.
256
rolePrimary :: String
257
rolePrimary = "primary"
258

    
259
-- | String for secondary role.
260
roleSecondary :: String
261
roleSecondary = "secondary"
262

    
263
-- | Gets the list of DRBD minors for an instance that are related to
264
-- a given node.
265
getInstMinorsForNode :: String -> Instance
266
                     -> [(String, Int, String, String, String, String)]
267
getInstMinorsForNode node inst =
268
  let role = if node == instPrimaryNode inst
269
               then rolePrimary
270
               else roleSecondary
271
      iname = instName inst
272
  -- FIXME: the disk/ build there is hack-ish; unify this in a
273
  -- separate place, or reuse the iv_name (but that is deprecated on
274
  -- the Python side)
275
  in concatMap (\(idx, dsk) ->
276
            [(node, minor, iname, "disk/" ++ show idx, role, peer)
277
               | (minor, peer) <- getDrbdMinorsForNode node dsk]) .
278
     zip [(0::Int)..] . instDisks $ inst
279

    
280
-- | Builds link -> ip -> instname map.
281
--
282
-- TODO: improve this by splitting it into multiple independent functions:
283
--
284
-- * abstract the \"fetch instance with filled params\" functionality
285
--
286
-- * abstsract the [instance] -> [(nic, instance_name)] part
287
--
288
-- * etc.
289
buildLinkIpInstnameMap :: ConfigData -> LinkIpMap
290
buildLinkIpInstnameMap cfg =
291
  let cluster = configCluster cfg
292
      instances = M.elems . fromContainer . configInstances $ cfg
293
      defparams = (M.!) (fromContainer $ clusterNicparams cluster) C.ppDefault
294
      nics = concatMap (\i -> [(instName i, nic) | nic <- instNics i])
295
             instances
296
  in foldl' (\accum (iname, nic) ->
297
               let pparams = nicNicparams nic
298
                   fparams = fillNicParams defparams pparams
299
                   link = nicpLink fparams
300
               in case nicIp nic of
301
                    Nothing -> accum
302
                    Just ip -> let oldipmap = M.findWithDefault M.empty
303
                                              link accum
304
                                   newipmap = M.insert ip iname oldipmap
305
                               in M.insert link newipmap accum
306
            ) M.empty nics
307

    
308

    
309
-- | Returns a node's group, with optional failure if we can't find it
310
-- (configuration corrupt).
311
getGroupOfNode :: ConfigData -> Node -> Maybe NodeGroup
312
getGroupOfNode cfg node =
313
  M.lookup (nodeGroup node) (fromContainer . configNodegroups $ cfg)
314

    
315
-- | Returns a node's ndparams, filled.
316
getNodeNdParams :: ConfigData -> Node -> Maybe FilledNDParams
317
getNodeNdParams cfg node = do
318
  group <- getGroupOfNode cfg node
319
  let gparams = getGroupNdParams cfg group
320
  return $ fillNDParams gparams (nodeNdparams node)
321

    
322
instance NdParamObject Node where
323
  getNdParamsOf = getNodeNdParams
324

    
325
instance NdParamObject NodeGroup where
326
  getNdParamsOf cfg = Just . getGroupNdParams cfg
327

    
328
instance NdParamObject Cluster where
329
  getNdParamsOf _ = Just . clusterNdparams