~ntt-pf-lab/nova/monkey_patch_notification

« back to all changes in this revision

Viewing changes to vendor/boto/boto/pyami/config.py

  • Committer: Jesse Andrews
  • Date: 2010-05-28 06:05:26 UTC
  • Revision ID: git-v1:bf6e6e718cdc7488e2da87b21e258ccc065fe499
initial commit

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (c) 2006,2007 Mitch Garnaat http://garnaat.org/
 
2
#
 
3
# Permission is hereby granted, free of charge, to any person obtaining a
 
4
# copy of this software and associated documentation files (the
 
5
# "Software"), to deal in the Software without restriction, including
 
6
# without limitation the rights to use, copy, modify, merge, publish, dis-
 
7
# tribute, sublicense, and/or sell copies of the Software, and to permit
 
8
# persons to whom the Software is furnished to do so, subject to the fol-
 
9
# lowing conditions:
 
10
#
 
11
# The above copyright notice and this permission notice shall be included
 
12
# in all copies or substantial portions of the Software.
 
13
#
 
14
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 
15
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
 
16
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
 
17
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
 
18
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 
19
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 
20
# IN THE SOFTWARE.
 
21
#
 
22
import StringIO, os, re
 
23
import ConfigParser
 
24
import boto
 
25
 
 
26
BotoConfigPath = '/etc/boto.cfg'
 
27
BotoConfigLocations = [BotoConfigPath]
 
28
if 'HOME' in os.environ:
 
29
    UserConfigPath = os.path.expanduser('~/.boto')
 
30
    BotoConfigLocations.append(UserConfigPath)
 
31
else:
 
32
    UserConfigPath = None
 
33
if 'BOTO_CONFIG' in os.environ:
 
34
    BotoConfigLocations.append(os.path.expanduser(os.environ['BOTO_CONFIG']))
 
35
 
 
36
class Config(ConfigParser.SafeConfigParser):
 
37
 
 
38
    def __init__(self, path=None, fp=None, do_load=True):
 
39
        ConfigParser.SafeConfigParser.__init__(self, {'working_dir' : '/mnt/pyami',
 
40
                                                      'debug' : '0'})
 
41
        if do_load:
 
42
            if path:
 
43
                self.load_from_path(path)
 
44
            elif fp:
 
45
                self.readfp(fp)
 
46
            else:
 
47
                self.read(BotoConfigLocations)
 
48
            if "AWS_CREDENTIAL_FILE" in os.environ:
 
49
                self.load_credential_file(os.path.expanduser(os.environ['AWS_CREDENTIAL_FILE']))
 
50
 
 
51
    def load_credential_file(self, path):
 
52
        """Load a credential file as is setup like the Java utilities"""
 
53
        c_data = StringIO.StringIO()
 
54
        c_data.write("[Credentials]\n")
 
55
        for line in open(path, "r").readlines():
 
56
            c_data.write(line.replace("AWSAccessKeyId", "aws_access_key_id").replace("AWSSecretKey", "aws_secret_access_key"))
 
57
        c_data.seek(0)
 
58
        self.readfp(c_data)
 
59
 
 
60
    def load_from_path(self, path):
 
61
        file = open(path)
 
62
        for line in file.readlines():
 
63
            match = re.match("^#import[\s\t]*([^\s^\t]*)[\s\t]*$", line)
 
64
            if match:
 
65
                extended_file = match.group(1)
 
66
                (dir, file) = os.path.split(path)
 
67
                self.load_from_path(os.path.join(dir, extended_file))
 
68
        self.read(path)
 
69
 
 
70
    def save_option(self, path, section, option, value):
 
71
        """
 
72
        Write the specified Section.Option to the config file specified by path.
 
73
        Replace any previous value.  If the path doesn't exist, create it.
 
74
        Also add the option the the in-memory config.
 
75
        """
 
76
        config = ConfigParser.SafeConfigParser()
 
77
        config.read(path)
 
78
        if not config.has_section(section):
 
79
            config.add_section(section)
 
80
        config.set(section, option, value)
 
81
        fp = open(path, 'w')
 
82
        config.write(fp)
 
83
        fp.close()
 
84
        if not self.has_section(section):
 
85
            self.add_section(section)
 
86
        self.set(section, option, value)
 
87
 
 
88
    def save_user_option(self, section, option, value):
 
89
        self.save_option(UserConfigPath, section, option, value)
 
90
 
 
91
    def save_system_option(self, section, option, value):
 
92
        self.save_option(BotoConfigPath, section, option, value)
 
93
 
 
94
    def get_instance(self, name, default=None):
 
95
        try:
 
96
            val = self.get('Instance', name)
 
97
        except:
 
98
            val = default
 
99
        return val
 
100
 
 
101
    def get_user(self, name, default=None):
 
102
        try:
 
103
            val = self.get('User', name)
 
104
        except:
 
105
            val = default
 
106
        return val
 
107
 
 
108
    def getint_user(self, name, default=0):
 
109
        try:
 
110
            val = self.getint('User', name)
 
111
        except:
 
112
            val = default
 
113
        return val
 
114
 
 
115
    def get_value(self, section, name, default=None):
 
116
        return self.get(section, name, default)
 
117
 
 
118
    def get(self, section, name, default=None):
 
119
        try:
 
120
            val = ConfigParser.SafeConfigParser.get(self, section, name)
 
121
        except:
 
122
            val = default
 
123
        return val
 
124
    
 
125
    def getint(self, section, name, default=0):
 
126
        try:
 
127
            val = ConfigParser.SafeConfigParser.getint(self, section, name)
 
128
        except:
 
129
            val = int(default)
 
130
        return val
 
131
    
 
132
    def getfloat(self, section, name, default=0.0):
 
133
        try:
 
134
            val = ConfigParser.SafeConfigParser.getfloat(self, section, name)
 
135
        except:
 
136
            val = float(default)
 
137
        return val
 
138
 
 
139
    def getbool(self, section, name, default=False):
 
140
        if self.has_option(section, name):
 
141
            val = self.get(section, name)
 
142
            if val.lower() == 'true':
 
143
                val = True
 
144
            else:
 
145
                val = False
 
146
        else:
 
147
            val = default
 
148
        return val
 
149
    
 
150
    def setbool(self, section, name, value):
 
151
        if value:
 
152
            self.set(section, name, 'true')
 
153
        else:
 
154
            self.set(section, name, 'false')
 
155
    
 
156
    def dump(self):
 
157
        s = StringIO.StringIO()
 
158
        self.write(s)
 
159
        print s.getvalue()
 
160
 
 
161
    def dump_safe(self, fp=None):
 
162
        if not fp:
 
163
            fp = StringIO.StringIO()
 
164
        for section in self.sections():
 
165
            fp.write('[%s]\n' % section)
 
166
            for option in self.options(section):
 
167
                if option == 'aws_secret_access_key':
 
168
                    fp.write('%s = xxxxxxxxxxxxxxxxxx\n' % option)
 
169
                else:
 
170
                    fp.write('%s = %s\n' % (option, self.get(section, option)))
 
171
    
 
172
    def dump_to_sdb(self, domain_name, item_name):
 
173
        import simplejson
 
174
        sdb = boto.connect_sdb()
 
175
        domain = sdb.lookup(domain_name)
 
176
        if not domain:
 
177
            domain = sdb.create_domain(domain_name)
 
178
        item = domain.new_item(item_name)
 
179
        item.active = False
 
180
        for section in self.sections():
 
181
            d = {}
 
182
            for option in self.options(section):
 
183
                d[option] = self.get(section, option)
 
184
            item[section] = simplejson.dumps(d)
 
185
        item.save()
 
186
 
 
187
    def load_from_sdb(self, domain_name, item_name):
 
188
        import simplejson
 
189
        sdb = boto.connect_sdb()
 
190
        domain = sdb.lookup(domain_name)
 
191
        item = domain.get_item(item_name)
 
192
        for section in item.keys():
 
193
            if not self.has_section(section):
 
194
                self.add_section(section)
 
195
            d = simplejson.loads(item[section])
 
196
            for attr_name in d.keys():
 
197
                attr_value = d[attr_name]
 
198
                if attr_value == None:
 
199
                    attr_value = 'None'
 
200
                if isinstance(attr_value, bool):
 
201
                    self.setbool(section, attr_name, attr_value)
 
202
                else:
 
203
                    self.set(section, attr_name, attr_value)