OSDN Git Service

ignore inactive pools. (ticket#94)
[karesansui/karesansui.git] / bin / export_guest.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 #
4 # This file is part of Karesansui.
5 #
6 # Copyright (C) 2009-2010 HDE, Inc.
7 #
8 # This program is free software; you can redistribute it and/or
9 # modify it under the terms of the GNU General Public License
10 # as published by the Free Software Foundation; either version 2
11 # of the License, or (at your option) any later version.
12 #
13
14 import os
15 import os.path
16 import sys
17 import signal
18 import logging
19 from optparse import OptionParser
20
21 from ksscommand import KssCommand, KssCommandException, KssCommandOptException
22
23 import __cmd__
24
25 try:
26     import karesansui
27     from karesansui import __version__
28     from karesansui.lib.virt.virt import KaresansuiVirtConnection, KaresansuiVirtException
29     from karesansui.lib.utils import load_locale, preprint_r, base64_decode
30     from karesansui.db.access.machine import findby1uniquekey
31     from karesansui.lib.utils import string_from_uuid     as StrFromUUID
32     from karesansui.lib.utils import generate_uuid        as GenUUID
33     from karesansui.lib.virt.snapshot import KaresansuiVirtSnapshot
34     from karesansui.db.access.snapshot import findbyname_guestby1 as s_findbyname_guestby1
35 except ImportError:
36     print >>sys.stderr, "[Error] karesansui package was not found."
37     sys.exit(1)
38
39 _ = load_locale()
40
41 usage = '%prog [options]'
42
43 def getopts():
44     optp = OptionParser(usage=usage, version=__version__)
45     optp.add_option('-n', '--name', dest='name', help=_('Domain name'))
46     optp.add_option('-p', '--pool', dest='pool', help=_('Storage pool name'))
47     #optp.add_option('-d', '--dir',  dest='dir',  help=_('Directory name'))
48     optp.add_option('-t', '--title',dest='title',default='', help=_('Export title'))
49     optp.add_option('-q', '--quiet',dest='verbose', action="store_false", default=True, help=_("don't print status messages"))
50     return optp.parse_args()
51
52 def chkopts(opts):
53     if not opts.name:
54         raise KssCommandOptException('ERROR: -n or --name option is required.')
55     #if not opts.pool and not opts.dir:
56     #    raise KssCommandOptException('ERROR: -p/--pool or -d/--dir options are required.')
57
58     # valid
59
60 class ExportGuest(KssCommand):
61
62     def __grab_stdout(self, flag):
63         if flag:
64                 self.stdout = sys.stdout
65                 sys.stdout = os.fdopen(sys.stdout.fileno(), "w", 0)
66                 logf = open("/dev/null", "a")
67                 os.dup2(logf.fileno(), 1)
68                 logf.close()
69         else:
70                 os.dup2(sys.stdout.fileno(), 1)
71                 sys.stdout = self.stdout
72                 del self.stdout
73
74     def process(self):
75         (opts, args) = getopts()
76         chkopts(opts)
77         self.up_progress(1)
78
79         conn = KaresansuiVirtConnection(readonly=False)
80         try:
81             try:
82                 src_pool = conn.get_storage_pool_name_bydomain(opts.name, "os")
83                 if not src_pool:
84                     raise KssCommandException("Source storage pool is not found.")
85                 if conn.get_storage_pool_type(src_pool) == 'dir':
86                     raise KssCommandException("Storage pool type 'dir' is not.")
87
88                 src_path = conn.get_storage_pool_targetpath(src_pool[0])
89                 self.domain_dir  = "%s/%s" % (src_path, opts.name,)
90
91                 if os.path.isdir(self.domain_dir) is False:
92                     raise KssCommandException(
93                         'domain directory is not found or not directory. - %s' % (self.domain_dir))
94
95
96                 # Model
97                 virt_uuid = conn.domname_to_uuid(opts.name)
98                 model = findby1uniquekey(self.kss_session, virt_uuid)
99                 if not model:
100                     raise KssCommandException("Export data does not exist in the database.")
101
102                 database = {}
103                 database['attribute'] = model.attribute
104                 database['hypervisor'] = model.hypervisor
105                 database['icon'] = model.icon
106                 database['name'] = model.name
107                 database['notebook'] = {"title" : model.notebook.title,
108                                      "value" : model.notebook.value,
109                                      }
110                 tags = []
111                 for _tag in model.tags:
112                     tags.append(_tag.name)
113
114                 database['tags'] = ",".join(tags)
115                 database['uniq_key'] = model.uniq_key
116
117                 # Snapshot
118                 #import pdb; pdb.set_trace()
119                 snapshots = []
120                 kvs = KaresansuiVirtSnapshot(readonly=False)
121                 try:
122                     guest_id = model.id
123                     snapshot_list = kvs.listNames(opts.name)[opts.name]
124                     if len(snapshot_list) > 0:
125                         for snapshot in snapshot_list:
126                             s_model = s_findbyname_guestby1(self.kss_session, snapshot, guest_id)
127                             if s_model is not None:
128                                 name  = s_model.name
129                                 title = s_model.notebook.title
130                                 value = s_model.notebook.value
131                                 snapshots.append({"name":name, "title":title, "value":value,})
132                 except:
133                     raise KssCommandException("Cannot fetch the information of snapshots correctly.")
134                 kvs.finish()
135
136                 # Pool
137                 target_dir = ""
138                 if opts.pool:
139                     pool = conn.search_kvn_storage_pools(opts.pool)
140                     storage_info = pool[0].get_info()
141                     if storage_info["type"] == "dir" and storage_info["target"]["path"] != "":
142                         target_dir = storage_info["target"]["path"]
143                 elif opts.dir:
144                     target_dir = opts.dir
145
146                 self.up_progress(1)
147
148                 progresscb = None
149                 if opts.verbose:
150                     try:
151                         from karesansui.lib.progress import ProgressMeter
152                         progresscb = ProgressMeter(command_object=self)
153                     except:
154                         pass
155                 else:
156                     try:
157                         from karesansui.lib.progress import ProgressMeter
158                         progresscb = ProgressMeter(command_object=self,quiet=True)
159                     except:
160                         pass
161
162                 if opts.title[0:4] == "b64:":
163                     title = base64_decode(opts.title[4:])
164                 else:
165                     title = opts.title
166
167                 uuid = StrFromUUID(GenUUID())
168                 conn.export_guest(uuid=uuid,
169                                   name=opts.name,
170                                   directory=target_dir,
171                                   database=database,
172                                   realicon=model.realicon(),
173                                   title=title,
174                                   snapshots=snapshots,
175                                   progresscb=progresscb)
176
177                 self.up_progress(40)
178                 self.logger.info('Export guest completed. - pool=%s, uuid=%s' % (opts.pool, uuid))
179                 print >>sys.stdout, _('Export guest completed. - pool=%s, uuid=%s' % (opts.pool, uuid))
180                 return True
181
182             except KaresansuiVirtException, e:
183                 raise KssCommandException('Failed to export guest. - %s to %s [%s]' \
184                                           % (opts.name,target_dir, ''.join(e.args)))
185             except:
186                 raise KssCommandException('Failed to export guest. - %s to %s' \
187                                           % (opts.name,target_dir))
188         finally:
189             conn.close()
190
191
192 if __name__ == "__main__":
193     target = ExportGuest()
194     sys.exit(target.run())