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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
|
#!/usr/bin/python
# vi: ts=4 expandtab
#
# Copyright (C) 2012 Canonical Ltd.
#
# Author: Scott Moser <scott.moser@canonical.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3, as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import argparse
import os
import shutil
import subprocess
import sys
import yaml
VERSION = "0.3.0"
SEED_DIR = "var/lib/cloud/seed"
SET_DS_CFG = 'etc/cloud/cloud.cfg.d/90_dpkg.cfg'
VAR_LIB_CLOUD = "var/lib/cloud"
VAR_LOG = "var/log"
KNOWN_LOGS = ["cloud-init.log", "cloud-init-output.log"]
KNOWN_DATASOURCES = [
'AltCloud',
'Azure',
'CloudStack',
'ConfigDrive',
'Ec2',
'MAAS',
'NoCloud',
'None',
'OpenNebula',
'OVF',
'SmartOS',
]
DEFAULT_METADATA = "instance-id: nocloud-static\n"
DEFAULT_USERDATA = """
#cloud-config
password: passw0rd
chpasswd: { expire: False }
ssh_pwauth: True
""".lstrip()
def seed(args, seed_dir=SEED_DIR):
sdir = os.path.join(args.target, seed_dir, args.seed)
(userdata, metadata) = (DEFAULT_USERDATA, DEFAULT_METADATA)
if not os.path.isdir(sdir):
os.makedirs(sdir)
if args.userdata not in ("default", None):
with open(args.userdata, "r") as fp:
userdata = fp.read()
if args.metadata:
with open(args.metadata, "r") as fp:
metadata = fp.read()
md = yaml.safe_load(metadata)
if not args.no_set_hostname:
hostname = md.get('local-hostname', md.get('hostname'))
if hostname is not None:
hfile = os.path.join(args.target, "etc/hostname")
set_hostname(hostname, hostname_file=hfile)
with open(os.path.join(sdir, 'user-data'), "w") as fp:
fp.write(userdata)
with open(os.path.join(sdir, 'meta-data'), "w") as fp:
fp.write(metadata)
def set_hostname(hostname, hostname_file):
with open(hostname_file, "w") as fp:
fp.write(hostname + "\n")
def clean_lib(varlibcloud=VAR_LIB_CLOUD, full=False, purge=False):
if purge:
removes = [varlibcloud]
else:
bnames= ['instance', 'instances', 'seed', 'sem']
if full:
bnames.extend(('data', 'handlers', 'scripts',))
removes = [os.path.join(varlibcloud, f) for f in bnames]
for r in removes:
rm_force(r)
def clean_logs(varlog=VAR_LOG, full=False):
removes = [os.path.join(varlog, r) for r in KNOWN_LOGS]
if full:
for bname in os.glob(os.path.join(varlog, 'cloud-init*')):
removes.append(os.path.join(varlog, bname))
for r in removes:
rm_force(r)
def reset(args):
clean_lib(varlibcloud=os.path.join(args.target, VAR_LIB_CLOUD),
full=args.full, purge=args.purge)
if args.logs:
clean_logs(varlog=os.path.join(args.target, VAR_LOG),
full=args.full)
return
def run(args):
print(args)
def set_ds(args):
# TODO: figure out the best way to handle target
if args.config_file is None:
cfg_path = os.path.join(args.target, SET_DS_CFG)
elif args.config_file == "-":
cfg_path = "-"
elif args.target is not None:
cfg_path = os.path.join(args.target, args.config_file)
else:
cfg_path = args.config_file
data = {'datasource_list': args.datasources}
known_ds = [f.lower() for f in KNOWN_DATASOURCES]
ds_list = []
for ds in args.datasources:
try:
ds_list.append(KNOWN_DATASOURCES[known_ds.index(ds.lower())])
except ValueError:
# probably should warn here about unknown datasource
ds_list.append(ds)
if cfg_path == "-":
fp = sys.stdout
else:
fp = open(cfg_path, "w")
fp.write(yaml.dump({'datasource_list': ds_list}) + "\n")
if cfg_path != "-":
fp.close()
def rm_force(path):
if os.path.islink(path):
os.unlink(path)
elif os.path.isdir(path):
shutil.rmtree(path)
elif os.path.exists(path):
os.unlink(path)
def main():
parser = argparse.ArgumentParser()
# Top level args
for (args, kwargs) in COMMON_ARGS:
parser.add_argument(*args, **kwargs)
subparsers = parser.add_subparsers()
for subcmd in sorted(SUBCOMMANDS.keys()):
val = SUBCOMMANDS[subcmd]
sparser = subparsers.add_parser(subcmd, help=val['help'])
sparser.set_defaults(action=(val.get('func'), val['func']))
for (args, kwargs) in val['opts']:
sparser.add_argument(*args, **kwargs)
args = parser.parse_args()
if not getattr(args, 'action', None):
# http://bugs.python.org/issue16308
parser.print_help()
sys.exit(1)
(name, functor) = args.action
functor(args)
SUBCOMMANDS = {
'reset': {
'func': reset, 'opts': [],
'help': 'remove logs and state files',
'opts': [
(('-F', '--full'),
{'help': 'be more complete in cleanup',
'default': False, 'action': 'store_true'}),
(('-P', '--purge'),
{'help': 'remove all of state directory (/var/lib/cloud)',
'default': False, 'action': 'store_true'}),
(('-l', '--logs'),
{'help': 'remove log files', 'default': False,
'action': 'store_true'}),
]
},
'run': {
'func': run, 'opts': [],
'help': 'execute cloud-init manually',
},
'set-ds': {
'func': set_ds, 'opts': [],
'help': 'set the datasource',
'opts': [
(('-f', '--config-file'),
{'help': 'output to specified cloud-config file',
'default': None}),
(('datasources',),
{'nargs': '+', 'metavar': 'DataSource'}),
]
},
'seed': {
'func': seed, 'help': 'populate the datasource',
'opts': [
(('-s', '--seed'),
{'action': 'store', 'default': 'nocloud-net',
'help': 'directory to populate with seed data',
'choices': ['nocloud-net', 'nocloud']}),
(('--no-set-hostname',),
{'action': 'store_true', 'default': False,
'help': 'do not attempt to set hostname based on metadata'}),
(('userdata',),
{'nargs': '?', 'default': None,
'help': 'use user-data from file', 'default': None}),
(('metadata',),
{'nargs': '?', 'default': None,
'help': 'use meta-data from file'}),
]
},
}
COMMON_ARGS = [
(('--version',), {'action': 'version', 'version': '%(prog)s ' + VERSION}),
(('--verbose', '-v'), {'action': 'count', 'default': 0}),
(('--target', '-t'), {'action': 'store', 'default': '/'}),
]
if __name__ == '__main__':
sys.exit(main())
|