Revision e0732b36 tools/cfgupgrade

b/tools/cfgupgrade
22 22
"""Tool to upgrade the configuration file.
23 23

  
24 24
This code handles only the types supported by simplejson. As an example, "set"
25
is a "list". Old Pickle based configurations files are converted to JSON during
26
the process.
25
is a "list".
27 26

  
28 27
"""
29 28

  
......
31 30
import os
32 31
import os.path
33 32
import sys
34
import re
35 33
import optparse
36 34
import tempfile
37 35
import simplejson
......
49 47
  pass
50 48

  
51 49

  
52
# {{{ Support for old Pickle files
53
class UpgradeDict(dict):
54
  """Base class for internal config classes.
55

  
56
  """
57
  def __setstate__(self, state):
58
    self.update(state)
59

  
60
  def __getstate__(self):
61
    return self.copy()
62

  
63

  
64
def FindGlobal(module, name):
65
  """Wraps Ganeti config classes to internal ones.
66

  
67
  This function may only return types supported by simplejson.
68

  
69
  """
70
  if module == "ganeti.objects":
71
    return UpgradeDict
72
  elif module == "__builtin__" and name == "set":
73
    return list
74

  
75
  return getattr(sys.modules[module], name)
76

  
77

  
78
def ReadPickleFile(f):
79
  """Reads an old Pickle configuration.
80

  
81
  """
82
  import cPickle
83

  
84
  loader = cPickle.Unpickler(f)
85
  loader.find_global = FindGlobal
86
  return loader.load()
87

  
88

  
89
def IsPickleFile(f):
90
  """Checks whether a file is using the Pickle format.
91

  
92
  """
93
  magic = f.read(128)
94
  try:
95
    return not re.match('^\s*\{', magic)
96
  finally:
97
    f.seek(-len(magic), 1)
98
# }}}
99

  
100

  
101
def ReadJsonFile(f):
102
  """Reads a JSON file.
103

  
104
  """
105
  return simplejson.load(f)
106

  
107

  
108 50
def ReadConfig(path):
109 51
  """Reads configuration file.
110 52

  
111 53
  """
112 54
  f = open(path, 'r')
113 55
  try:
114
    if IsPickleFile(f):
115
      return ReadPickleFile(f)
116
    else:
117
      return ReadJsonFile(f)
56
    return simplejson.load(f)
118 57
  finally:
119 58
    f.close()
120 59

  

Also available in: Unified diff