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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
|
"""Interactive configuration support for Landscape.
This module, and specifically L{BrokerConfigurationScript}, implements the
support for the C{landscape-config} script.
"""
import sys
import os
import getpass
from dbus import DBusException
from landscape.sysvconfig import SysVConfig, ProcessError
from landscape.lib.dbus_util import (
get_bus, NoReplyError, ServiceUnknownError, SecurityError)
from landscape.lib.twisted_util import gather_results
from landscape.broker.registration import InvalidCredentialsError
from landscape.broker.deployment import BrokerConfiguration
from landscape.broker.remote import RemoteBroker
from landscape.reactor import TwistedReactor
def print_text(text, end="\n", error=False):
if error:
stream = sys.stderr
else:
stream = sys.stdout
stream.write(text+end)
stream.flush()
def check_config(*args):
names = args
def decorator(function):
def decorated(*args, **kwargs):
self = args[0]
for name in names:
if name in self.config.get_command_line_options():
break
else:
function(*args, **kwargs)
return decorated
return decorator
class BrokerConfigurationScript(object):
"""
An interactive procedure which manages the prompting and temporary storage
of configuration parameters.
Various attributes on this object will be set on C{config} after L{run} is
called.
@ivar config: The L{BrokerConfiguration} object to read and set values from
and to.
"""
def __init__(self, config):
self.config = config
def show_help(self, text):
lines = text.strip().splitlines()
print_text("\n"+"".join([line.strip()+"\n" for line in lines]))
def prompt(self, option, msg, required=False):
"""Prompt the user on the terminal for a value.
@param option: The attribute of C{self.config} that contains the
default and which the value will be assigned to.
@param msg: The message to prompt the user with (via C{raw_input}).
@param required: If True, the user will be required to enter a value
before continuing.
"""
default = getattr(self.config, option, None)
if default:
msg += " [%s]: " % default
else:
msg += ": "
while True:
value = raw_input(msg)
if value:
setattr(self.config, option, value)
break
elif default or not required:
break
self.show_help("This option is required to configure Landscape.")
def password_prompt(self, option, msg, required=False):
"""Prompt the user on the terminal for a password and mask the value.
This also prompts the user twice and errors if both values don't match.
@param option: The attribute of C{self.config} that contains the
default and which the value will be assigned to.
@param msg: The message to prompt the user with (via C{raw_input}).
@param required: If True, the user will be required to enter a value
before continuing.
"""
default = getattr(self.config, option, None)
msg += ": "
while True:
value = getpass.getpass(msg)
if value:
value2 = getpass.getpass("Please confirm: ")
if value:
if value != value2:
self.show_help("Passwords must match.")
else:
setattr(self.config, option, value)
break
elif default or not required:
break
else:
self.show_help("This option is required to configure "
"Landscape.")
def prompt_yes_no(self, message, default=True):
if default:
default_msg = " [Y/n]"
else:
default_msg = " [y/N]"
while True:
value = raw_input(message + default_msg).lower()
if value:
if value.startswith("n"):
return False
if value.startswith("y"):
return True
self.show_help("Invalid input.")
else:
return default
@check_config("computer_title")
def query_computer_title(self):
self.show_help(
"""
The computer title you provide will be used to represent this
computer in the Landscape user interface. It's important to use
a title that will allow the system to be easily recognized when
it appears on the pending computers page.
""")
self.prompt("computer_title", "This computer's title", True)
@check_config("account_name")
def query_account_name(self):
self.show_help(
"""
You must now specify the name of the Landscape account you
want to register this computer with. You can verify the
names of the accounts you manage on your dashboard at
https://landscape.canonical.com/dashboard
""")
self.prompt("account_name", "Account name", True)
@check_config("registration_password")
def query_registration_password(self):
self.show_help(
"""
A registration password may be associated with your Landscape
account to prevent unauthorized registration attempts. This
is not your personal login password. It is optional, and unless
explicitly set on the server, it may be skipped here.
If you don't remember the registration password you can find it
at https://landscape.canonical.com/account/%s
""" % self.config.account_name)
self.password_prompt("registration_password",
"Account registration password")
@check_config("http_proxy", "https_proxy")
def query_proxies(self):
self.show_help(
"""
The Landscape client communicates with the server over HTTP and
HTTPS. If your network requires you to use a proxy to access HTTP
and/or HTTPS web sites, please provide the address of these
proxies now. If you don't use a proxy, leave these fields empty.
""")
self.prompt("http_proxy", "HTTP proxy URL")
self.prompt("https_proxy", "HTTPS proxy URL")
@check_config("include_manager_plugins", "script_users")
def query_script_plugin(self):
self.show_help(
"""
Landscape has a feature which enables administrators to run
arbitrary scripts on machines under their control. By default this
feature is disabled in the client, disallowing any arbitrary script
execution. If enabled, the set of users that scripts may run as is
also configurable.
""")
msg = "Enable script execution?"
included_plugins = getattr(self.config, "include_manager_plugins")
if not included_plugins:
included_plugins = ""
included_plugins = [x.strip() for x in included_plugins.split(",")]
if included_plugins == [""]:
included_plugins = []
default = "ScriptExecution" in included_plugins
if self.prompt_yes_no(msg, default=default):
if "ScriptExecution" not in included_plugins:
included_plugins.append("ScriptExecution")
self.show_help(
"""
By default, scripts are restricted to the 'landscape' and
'nobody' users. Please enter a comma-delimited list of users
that scripts will be restricted to. To allow scripts to be run
by any user, enter "ALL".
""")
self.prompt("script_users", "Script users")
else:
if "ScriptExecution" in included_plugins:
included_plugins.remove("ScriptExecution")
self.config.include_manager_plugins = ', '.join(included_plugins)
def show_header(self):
self.show_help(
"""
This script will interactively set up the Landscape client. It will
ask you a few questions about this computer and your Landscape
account, and will submit that information to the Landscape server.
After this computer is registered it will need to be approved by an
account administrator on the pending computers page.
Please see https://landscape.canonical.com for more information.
""")
def run(self):
"""Kick off the interactive process which prompts the user for data.
Data will be saved to C{self.config}.
"""
self.show_header()
self.query_computer_title()
self.query_account_name()
self.query_registration_password()
self.query_proxies()
self.query_script_plugin()
def setup_init_script():
sysvconfig = SysVConfig()
if not sysvconfig.is_configured_to_run():
answer = raw_input("\nThe Landscape client must be started "
"on boot to operate correctly.\n\n"
"Start Landscape client on boot? (Y/n): ")
if not answer.upper().startswith("N"):
sysvconfig.set_start_on_boot(True)
try:
sysvconfig.start_landscape()
except ProcessError:
print_text("Error starting client cannot continue.")
sys.exit(-1)
else:
sys.exit("Aborting Landscape configuration")
def setup(args):
"""Prompt the user for config data and write out a configuration file."""
config = BrokerConfiguration()
config.load(args)
if not config.no_start:
setup_init_script()
if config.http_proxy is None and os.environ.get("http_proxy"):
config.http_proxy = os.environ["http_proxy"]
if config.https_proxy is None and os.environ.get("https_proxy"):
config.https_proxy = os.environ["https_proxy"]
script = BrokerConfigurationScript(config)
script.run()
config.write()
return config
def register(config, reactor=None):
"""Instruct the Landscape Broker to register the client.
The broker will be instructed to reload its configuration and then to
attempt a registration.
"""
from twisted.internet.glib2reactor import install
install()
# please only pass reactor when you have totally mangled everything with
# mocker. Otherwise bad things will happen.
if reactor is None:
from twisted.internet import reactor
def failure():
print_text("Invalid account name or "
"registration password.", error=True)
reactor.stop()
def success():
print_text("System successfully registered.")
reactor.stop()
def exchange_failure():
print_text("We were unable to contact the server. "
"Your internet connection may be down. "
"The landscape client will continue to try and contact "
"the server periodically.",
error=True)
reactor.stop()
def handle_registration_errors(failure):
# We'll get invalid credentials through the signal.
error = failure.trap(InvalidCredentialsError, NoReplyError)
# This event is fired here so we can catch this case where
# there is no reply in a test. In the normal case when
# running the client there is no trigger added for this event
# and it is essentially a noop.
reactor.fireSystemEvent("landscape-registration-error")
def catch_all(failure):
# We catch SecurityError here too, because on some DBUS configurations
# if you try to connect to a dbus name that doesn't have a listener,
# it'll try auto-starting the service, but then the StartServiceByName
# call can raise a SecurityError.
if failure.check(ServiceUnknownError, SecurityError):
print_text("Error occurred contacting Landscape Client. "
"Is it running?", error=True)
else:
print_text(failure.getTraceback(), error=True)
print_text("Unknown error occurred.", error=True)
reactor.callLater(0, reactor.stop)
print_text("Please wait... ", "")
remote = RemoteBroker(get_bus(config.bus), retry_timeout=0)
# This is a bit unfortunate. Every method of remote returns a deferred,
# even stuff like connect_to_signal, because the fetching of the DBus
# object itself is asynchronous. We can *mostly* fire-and-forget these
# things, except that if the object isn't found, *all* of the deferreds
# will fail. To prevent unhandled errors, we need to collect them all up
# and add an errback.
deferreds = [
remote.reload_configuration(),
remote.connect_to_signal("registration_done", success),
remote.connect_to_signal("registration_failed", failure),
remote.connect_to_signal("exchange_failed", exchange_failure),
remote.register().addErrback(handle_registration_errors)]
# We consume errors here to ignore errors after the first one. catch_all
# will be called for the very first deferred that fails.
gather_results(deferreds, consume_errors=True).addErrback(catch_all)
reactor.run()
def main(args):
config = setup(args)
answer = raw_input("\nRequest a new registration for "
"this computer now? (Y/n): ")
if not answer.upper().startswith("N"):
register(config)
|