1# Copyright (c) 2006-2010 Mitch Garnaat http://garnaat.org/
2# Copyright (c) 2010, Eucalyptus Systems, Inc.
3#
4# Permission is hereby granted, free of charge, to any person obtaining a
5# copy of this software and associated documentation files (the
6# "Software"), to deal in the Software without restriction, including
7# without limitation the rights to use, copy, modify, merge, publish, dis-
8# tribute, sublicense, and/or sell copies of the Software, and to permit
9# persons to whom the Software is furnished to do so, subject to the fol-
10# lowing conditions:
11#
12# The above copyright notice and this permission notice shall be included
13# in all copies or substantial portions of the Software.
14#
15# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
16# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
17# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
18# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
19# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21# IN THE SOFTWARE.
22
23"""
24Represents an EC2 Object
25"""
26from boto.ec2.tag import TagSet
27
28
29class EC2Object(object):
30
31    def __init__(self, connection=None):
32        self.connection = connection
33        if self.connection and hasattr(self.connection, 'region'):
34            self.region = connection.region
35        else:
36            self.region = None
37
38    def startElement(self, name, attrs, connection):
39        return None
40
41    def endElement(self, name, value, connection):
42        setattr(self, name, value)
43
44
45class TaggedEC2Object(EC2Object):
46    """
47    Any EC2 resource that can be tagged should be represented
48    by a Python object that subclasses this class.  This class
49    has the mechanism in place to handle the tagSet element in
50    the Describe* responses.  If tags are found, it will create
51    a TagSet object and allow it to parse and collect the tags
52    into a dict that is stored in the "tags" attribute of the
53    object.
54    """
55
56    def __init__(self, connection=None):
57        super(TaggedEC2Object, self).__init__(connection)
58        self.tags = TagSet()
59
60    def startElement(self, name, attrs, connection):
61        if name == 'tagSet':
62            return self.tags
63        else:
64            return None
65
66    def add_tag(self, key, value='', dry_run=False):
67        """
68        Add a tag to this object.  Tags are stored by AWS and can be used
69        to organize and filter resources.  Adding a tag involves a round-trip
70        to the EC2 service.
71
72        :type key: str
73        :param key: The key or name of the tag being stored.
74
75        :type value: str
76        :param value: An optional value that can be stored with the tag.
77                      If you want only the tag name and no value, the
78                      value should be the empty string.
79        """
80        self.add_tags({key: value}, dry_run)
81
82    def add_tags(self, tags, dry_run=False):
83        """
84        Add tags to this object.  Tags are stored by AWS and can be used
85        to organize and filter resources.  Adding tags involves a round-trip
86        to the EC2 service.
87
88        :type tags: dict
89        :param tags: A dictionary of key-value pairs for the tags being stored.
90                     If for some tags you want only the name and no value, the
91                     corresponding value for that tag name should be an empty
92                     string.
93        """
94        status = self.connection.create_tags(
95            [self.id],
96            tags,
97            dry_run=dry_run
98        )
99        if self.tags is None:
100            self.tags = TagSet()
101        self.tags.update(tags)
102
103    def remove_tag(self, key, value=None, dry_run=False):
104        """
105        Remove a tag from this object.  Removing a tag involves a round-trip
106        to the EC2 service.
107
108        :type key: str
109        :param key: The key or name of the tag being stored.
110
111        :type value: str
112        :param value: An optional value that can be stored with the tag.
113                      If a value is provided, it must match the value currently
114                      stored in EC2.  If not, the tag will not be removed.  If
115                      a value of None is provided, the tag will be
116                      unconditionally deleted.
117                      NOTE: There is an important distinction between a value
118                      of '' and a value of None.
119        """
120        self.remove_tags({key: value}, dry_run)
121
122    def remove_tags(self, tags, dry_run=False):
123        """
124        Removes tags from this object.  Removing tags involves a round-trip
125        to the EC2 service.
126
127        :type tags: dict
128        :param tags: A dictionary of key-value pairs for the tags being removed.
129                     For each key, the provided value must match the value
130                     currently stored in EC2.  If not, that particular tag will
131                     not be removed.  However, if a value of None is provided,
132                     the tag will be unconditionally deleted.
133                     NOTE: There is an important distinction between a value of
134                     '' and a value of None.
135        """
136        status = self.connection.delete_tags(
137            [self.id],
138            tags,
139            dry_run=dry_run
140        )
141        for key, value in tags.items():
142            if key in self.tags:
143                if value is None or value == self.tags[key]:
144                    del self.tags[key]
145