Statistics
| Branch: | Tag: | Revision:

root / src / Ganeti / Config.hs @ 4e6f1cde

History | View | Annotate | Download (14.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
    , getInstAllNodes
48
    , getFilledInstHvParams
49
    , getFilledInstBeParams
50
    , getFilledInstOsParams
51
    , getNetwork
52
    , buildLinkIpInstnameMap
53
    , instNodes
54
    ) where
55

    
56
import Control.Monad (liftM)
57
import Data.List (foldl', nub)
58
import qualified Data.Map as M
59
import qualified Data.Set as S
60
import qualified Text.JSON as J
61

    
62
import Ganeti.BasicTypes
63
import qualified Ganeti.ConstantUtils as C
64
import qualified Ganeti.Constants as C
65
import Ganeti.Errors
66
import Ganeti.JSON
67
import Ganeti.Objects
68
import Ganeti.Types
69

    
70
-- | Type alias for the link and ip map.
71
type LinkIpMap = M.Map String (M.Map String String)
72

    
73
-- | Type class denoting objects which have node parameters.
74
class NdParamObject a where
75
  getNdParamsOf :: ConfigData -> a -> Maybe FilledNDParams
76

    
77
-- | Reads the config file.
78
readConfig :: FilePath -> IO String
79
readConfig = readFile
80

    
81
-- | Parses the configuration file.
82
parseConfig :: String -> Result ConfigData
83
parseConfig = fromJResult "parsing configuration" . J.decodeStrict
84

    
85
-- | Wrapper over 'readConfig' and 'parseConfig'.
86
loadConfig :: FilePath -> IO (Result ConfigData)
87
loadConfig = fmap parseConfig . readConfig
88

    
89
-- * Query functions
90

    
91
-- | Computes the nodes covered by a disk.
92
computeDiskNodes :: Disk -> S.Set String
93
computeDiskNodes dsk =
94
  case diskLogicalId dsk of
95
    LIDDrbd8 nodeA nodeB _ _ _ _ -> S.fromList [nodeA, nodeB]
96
    _ -> S.empty
97

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

    
104
-- | Computes all nodes of an instance.
105
instNodes :: Instance -> S.Set String
106
instNodes inst = instPrimaryNode inst `S.insert` instDiskNodes inst
107

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

    
115
-- | Get instances of a given node.
116
-- The node is specified through its UUID.
117
getNodeInstances :: ConfigData -> String -> ([Instance], [Instance])
118
getNodeInstances cfg nname =
119
    let all_inst = M.elems . fromContainer . configInstances $ cfg
120
        pri_inst = filter ((== nname) . instPrimaryNode) all_inst
121
        sec_inst = filter ((nname `S.member`) . instSecondaryNodes) all_inst
122
    in (pri_inst, sec_inst)
123

    
124
-- | Computes the role of a node.
125
getNodeRole :: ConfigData -> Node -> NodeRole
126
getNodeRole cfg node
127
  | nodeName node == clusterMasterNode (configCluster cfg) = NRMaster
128
  | nodeMasterCandidate node = NRCandidate
129
  | nodeDrained node = NRDrained
130
  | nodeOffline node = NROffline
131
  | otherwise = NRRegular
132

    
133
-- | Returns the default cluster link.
134
getDefaultNicLink :: ConfigData -> String
135
getDefaultNicLink =
136
  nicpLink . (M.! C.ppDefault) . fromContainer .
137
  clusterNicparams . configCluster
138

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

    
149
-- | Returns instances of a given link.
150
getInstancesIpByLink :: LinkIpMap -> String -> [String]
151
getInstancesIpByLink linkipmap link =
152
  M.keys $ M.findWithDefault M.empty link linkipmap
153

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

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

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

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

    
202
-- | Computes a node group's node params.
203
getGroupNdParams :: ConfigData -> NodeGroup -> FilledNDParams
204
getGroupNdParams cfg ng =
205
  fillNDParams (clusterNdparams $ configCluster cfg) (groupNdparams ng)
206

    
207
-- | Computes a node group's ipolicy.
208
getGroupIpolicy :: ConfigData -> NodeGroup -> FilledIPolicy
209
getGroupIpolicy cfg ng =
210
  fillIPolicy (clusterIpolicy $ configCluster cfg) (groupIpolicy ng)
211

    
212
-- | Computes a group\'s (merged) disk params.
213
getGroupDiskParams :: ConfigData -> NodeGroup -> DiskParams
214
getGroupDiskParams cfg ng =
215
  GenericContainer $
216
  fillDict (fromContainer . clusterDiskparams $ configCluster cfg)
217
           (fromContainer $ groupDiskparams ng) []
218

    
219
-- | Get nodes of a given node group.
220
getGroupNodes :: ConfigData -> String -> [Node]
221
getGroupNodes cfg gname =
222
  let all_nodes = M.elems . fromContainer . configNodes $ cfg in
223
  filter ((==gname) . nodeGroup) all_nodes
224

    
225
-- | Get (primary, secondary) instances of a given node group.
226
getGroupInstances :: ConfigData -> String -> ([Instance], [Instance])
227
getGroupInstances cfg gname =
228
  let gnodes = map nodeUuid (getGroupNodes cfg gname)
229
      ginsts = map (getNodeInstances cfg) gnodes in
230
  (concatMap fst ginsts, concatMap snd ginsts)
231

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

    
244
-- | Retrieves the instance hypervisor params, missing values filled with
245
-- cluster defaults.
246
getFilledInstHvParams :: ConfigData -> Instance -> HvParams
247
getFilledInstHvParams cfg inst =
248
  -- First get the defaults of the parent
249
  let hvName = hypervisorToRaw . instHypervisor $ inst
250
      hvParamMap = fromContainer . clusterHvparams $ configCluster cfg
251
      parentHvParams = maybe M.empty fromContainer $ M.lookup hvName hvParamMap
252
  -- Then the os defaults for the given hypervisor
253
      osName = instOs inst
254
      osParamMap = fromContainer . clusterOsHvp $ configCluster cfg
255
      osHvParamMap = maybe M.empty fromContainer $ M.lookup osName osParamMap
256
      osHvParams = maybe M.empty fromContainer $ M.lookup hvName osHvParamMap
257
  -- Then the child
258
      childHvParams = fromContainer . instHvparams $ inst
259
  -- Helper function
260
      fillFn con val = fillDict con val $ C.toList C.hvcGlobals
261
  in GenericContainer $ fillFn (fillFn parentHvParams osHvParams) childHvParams
262

    
263
-- | Retrieves the instance backend params, missing values filled with cluster
264
-- defaults.
265
getFilledInstBeParams :: ConfigData -> Instance -> ErrorResult FilledBeParams
266
getFilledInstBeParams cfg inst = do
267
  let beParamMap = fromContainer . clusterBeparams . configCluster $ cfg
268
  parentParams <- getItem "FilledBeParams" C.ppDefault beParamMap
269
  return $ fillBeParams parentParams (instBeparams inst)
270

    
271
-- | Retrieves the instance os params, missing values filled with cluster
272
-- defaults.
273
getFilledInstOsParams :: ConfigData -> Instance -> OsParams
274
getFilledInstOsParams cfg inst =
275
  let osLookupName = takeWhile (/= '+') (instOs inst)
276
      osParamMap = fromContainer . clusterOsparams $ configCluster cfg
277
      childOsParams = instOsparams inst
278
  in case getItem "OsParams" osLookupName osParamMap of
279
       Ok parentOsParams -> GenericContainer $
280
                              fillDict (fromContainer parentOsParams)
281
                                       (fromContainer childOsParams) []
282
       Bad _             -> childOsParams
283

    
284
-- | Looks up an instance's primary node.
285
getInstPrimaryNode :: ConfigData -> String -> ErrorResult Node
286
getInstPrimaryNode cfg name =
287
  liftM instPrimaryNode (getInstance cfg name) >>= getNode cfg
288

    
289
-- | Retrieves all nodes hosting a DRBD disk
290
getDrbdDiskNodes :: ConfigData -> Disk -> [Node]
291
getDrbdDiskNodes cfg disk =
292
  let retrieved = case diskLogicalId disk of
293
                    LIDDrbd8 nodeA nodeB _ _ _ _ ->
294
                      justOk [getNode cfg nodeA, getNode cfg nodeB]
295
                    _                            -> []
296
  in retrieved ++ concatMap (getDrbdDiskNodes cfg) (diskChildren disk)
297

    
298
-- | Retrieves all the nodes of the instance.
299
--
300
-- As instances not using DRBD can be sent as a parameter as well,
301
-- the primary node has to be appended to the results.
302
getInstAllNodes :: ConfigData -> String -> ErrorResult [Node]
303
getInstAllNodes cfg name = do
304
  inst <- getInstance cfg name
305
  let diskNodes = concatMap (getDrbdDiskNodes cfg) $ instDisks inst
306
  pNode <- getInstPrimaryNode cfg name
307
  return . nub $ pNode:diskNodes
308

    
309
-- | Filters DRBD minors for a given node.
310
getDrbdMinorsForNode :: String -> Disk -> [(Int, String)]
311
getDrbdMinorsForNode node disk =
312
  let child_minors = concatMap (getDrbdMinorsForNode node) (diskChildren disk)
313
      this_minors =
314
        case diskLogicalId disk of
315
          LIDDrbd8 nodeA nodeB _ minorA minorB _
316
            | nodeA == node -> [(minorA, nodeB)]
317
            | nodeB == node -> [(minorB, nodeA)]
318
          _ -> []
319
  in this_minors ++ child_minors
320

    
321
-- | String for primary role.
322
rolePrimary :: String
323
rolePrimary = "primary"
324

    
325
-- | String for secondary role.
326
roleSecondary :: String
327
roleSecondary = "secondary"
328

    
329
-- | Gets the list of DRBD minors for an instance that are related to
330
-- a given node.
331
getInstMinorsForNode :: String -> Instance
332
                     -> [(String, Int, String, String, String, String)]
333
getInstMinorsForNode node inst =
334
  let role = if node == instPrimaryNode inst
335
               then rolePrimary
336
               else roleSecondary
337
      iname = instName inst
338
  -- FIXME: the disk/ build there is hack-ish; unify this in a
339
  -- separate place, or reuse the iv_name (but that is deprecated on
340
  -- the Python side)
341
  in concatMap (\(idx, dsk) ->
342
            [(node, minor, iname, "disk/" ++ show idx, role, peer)
343
               | (minor, peer) <- getDrbdMinorsForNode node dsk]) .
344
     zip [(0::Int)..] . instDisks $ inst
345

    
346
-- | Builds link -> ip -> instname map.
347
--
348
-- TODO: improve this by splitting it into multiple independent functions:
349
--
350
-- * abstract the \"fetch instance with filled params\" functionality
351
--
352
-- * abstsract the [instance] -> [(nic, instance_name)] part
353
--
354
-- * etc.
355
buildLinkIpInstnameMap :: ConfigData -> LinkIpMap
356
buildLinkIpInstnameMap cfg =
357
  let cluster = configCluster cfg
358
      instances = M.elems . fromContainer . configInstances $ cfg
359
      defparams = (M.!) (fromContainer $ clusterNicparams cluster) C.ppDefault
360
      nics = concatMap (\i -> [(instName i, nic) | nic <- instNics i])
361
             instances
362
  in foldl' (\accum (iname, nic) ->
363
               let pparams = nicNicparams nic
364
                   fparams = fillNicParams defparams pparams
365
                   link = nicpLink fparams
366
               in case nicIp nic of
367
                    Nothing -> accum
368
                    Just ip -> let oldipmap = M.findWithDefault M.empty
369
                                              link accum
370
                                   newipmap = M.insert ip iname oldipmap
371
                               in M.insert link newipmap accum
372
            ) M.empty nics
373

    
374

    
375
-- | Returns a node's group, with optional failure if we can't find it
376
-- (configuration corrupt).
377
getGroupOfNode :: ConfigData -> Node -> Maybe NodeGroup
378
getGroupOfNode cfg node =
379
  M.lookup (nodeGroup node) (fromContainer . configNodegroups $ cfg)
380

    
381
-- | Returns a node's ndparams, filled.
382
getNodeNdParams :: ConfigData -> Node -> Maybe FilledNDParams
383
getNodeNdParams cfg node = do
384
  group <- getGroupOfNode cfg node
385
  let gparams = getGroupNdParams cfg group
386
  return $ fillNDParams gparams (nodeNdparams node)
387

    
388
instance NdParamObject Node where
389
  getNdParamsOf = getNodeNdParams
390

    
391
instance NdParamObject NodeGroup where
392
  getNdParamsOf cfg = Just . getGroupNdParams cfg
393

    
394
instance NdParamObject Cluster where
395
  getNdParamsOf _ = Just . clusterNdparams