-
Notifications
You must be signed in to change notification settings - Fork 0
/
oscmd
executable file
·141 lines (122 loc) · 5.25 KB
/
oscmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
#!/usr/bin/python
#
import os
import sys
# add boto module in PYTHONPATH if available
import os.path as osp
import boto
import oslib
from oslib.ec2_objects import ec2_objects
import oslib.b3_objects
import optparse
from oslib.context import Context
import codecs
import locale
# needed because default unicode to ascii encoding is strict
# we will use replace instead
def unicodetoascii(string):
return codecs.encode(string, output_locale, 'replace')
output_locale = locale.getpreferredencoding()
if len(output_locale) == 0:
output_locale = "US-ASCII"
def print_run_phrase(context, ec2_object, verb, args=None, **kwargs):
(cmd, executed) = oslib.run_phrase(context, ec2_object, verb, args, **kwargs)
if cmd is None:
print "invalid phrase '%s %s'" % (ec2_object.name, verb)
return 255
# If execute return a generator, iterate other it
if executed.__class__.__name__ == 'generator':
for s in executed:
if s != None:
string = cmd.to_str(s)
if string:
print unicodetoascii(string),
sys.stdout.flush()
return cmd.status()
# Else if it return something, just print it
elif executed != None and executed:
string = cmd.to_str(executed)
if string:
print unicodetoascii(string),
return cmd.status()
#It return false, something went wrong
elif executed != None:
print "'%s %s' failed" % (ec2_object.name, verb)
return 255
def main():
default_config = None
if 'OSCONFIG' in os.environ:
default_config = os.environ['OSCONFIG']
usage_common = "usage: %prog [options] object [object_args] verb [verbs_args]"
#The first level parser
parser = optparse.OptionParser(usage="%s\nobjects are:\n %s" % (usage_common, "\n ".join(oslib.objects.keys())))
parser.disable_interspersed_args()
parser.add_option("-c", "--config", dest="config_file", help="an alternative config file", default=default_config)
parser.add_option("-z", "--zone", dest="zone_name", help="zone name", default=None)
parser.add_option("-e", "--endpoint", dest="endpoint", help="endpoint URL", default=None)
parser.add_option("-L", "--listzone", dest="listzone", help="endpoint URL", default=False, action='store_true')
parser.add_option("-S", "--securitycredentials", dest="security_credentials", help="extract token from security credential", default=False)
parser.add_option("-d", "--debuglevel", dest="debug", help="The debug level", default=None, type="int")
(options, args) = parser.parse_args()
#Extract the context from the first level arguments
try:
kwargs = {}
for option_name in ('config_file', 'zone_name', 'endpoint', 'security_credentials', 'debug'):
value = getattr(options, option_name, None)
if value:
kwargs[option_name] = value
context = Context(**kwargs)
except boto.exception.NoAuthHandlerFound:
print """AWS authentication failed, did you setup $HOME/.boto ?"""
print "A sample can be found at %s/dotboto.sample" % os.path.dirname(os.path.abspath(oslib.__file__))
return 1
except boto.exception.EC2ResponseError as e:
if e.error_code == 'AuthFailure':
print "connection failed, bad security token"
return 254
else:
raise e
if options.listzone:
for z in context.cnx_ec2.get_all_zones():
print "%s:%s" % (z.region.name, z.name)
return 0
if len(args) > 0:
#A object is found try to resolve the verb
ec2_object_name = args.pop(0)
if ec2_object_name in ec2_objects:
ec2_object_type = ec2_objects[ec2_object_name]
else:
ec2_object_type = None
if not ec2_object_name in oslib.objects:
print 'unknonw object: %s' % ec2_object_name
return 253
#The object parser
parser_object = optparse.OptionParser()
parser_object.disable_interspersed_args()
parser_object.add_option("-i", "--id", dest="id", help="object ID", default=None)
parser_object.add_option("-n", "--name", dest="name", help="object tag 'Name'", default=None)
parser_object.set_usage("%s\nverbs are:\n %s" % (usage_common, "\n ".join(oslib.objects[ec2_object_name].keys())))
if ec2_object_type and 'set_parser' in ec2_object_type.__dict__:
ec2_object_type.set_parser(parser_object)
(object_options, object_args) = parser_object.parse_args(args)
if len(object_args) > 0:
verb = object_args.pop(0)
if ec2_object_type:
ec2_object = ec2_object_type(context, **vars(object_options))
else:
ec2_object = None
try:
status = print_run_phrase(context, ec2_object, verb, object_args)
sys.exit(status)
except (boto.exception.EC2ResponseError, oslib.OSLibError) as e:
print "The action \"%s %s\" failed with \"%s\"" % (ec2_object.name, verb, e.error_message)
else:
print 'verb missing'
else:
print 'object missing'
return 253
if __name__ == "__main__":
try:
sys.exit(main())
except KeyboardInterrupt:
sys.exit(1)