summaryrefslogtreecommitdiffstats
path: root/cobbler/api.py
blob: ebe987ecc1b88c7b81a8851ae4281cce84545f3b (plain)
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
"""
python API module for Cobbler
see source for cobbler.py, or pydoc, for example usage.
CLI apps and daemons should import api.py, and no other cobbler code.

Copyright 2006, Red Hat, Inc
Michael DeHaan <mdehaan@redhat.com>

This software may be freely redistributed under the terms of the GNU
general public license.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
"""

import config
import utils
import action_sync
import action_check
import action_import
import action_reposync
import action_status
import action_validate
from cexceptions import *
import sub_process
import module_loader
import kickgen

import logging
import os
import fcntl
from utils import _

ERROR = 100
INFO  = 10
DEBUG = 5

# notes on locking:
# BootAPI is a singleton object
# the XMLRPC variants allow 1 simultaneous request
# therefore we flock on /var/lib/cobbler/settings for now
# on a request by request basis.

class BootAPI:


    __shared_state = {}
    __has_loaded = False

    def __init__(self):
        """
        Constructor
        """

        self.__dict__ = BootAPI.__shared_state
        if not BootAPI.__has_loaded:

            # NOTE: we do not log all API actions, because
            # a simple CLI invocation may call adds and such
            # to load the config, which would just fill up
            # the logs, so we'll do that logging at CLI
            # level (and remote.py web service level) instead.

            self.logger = self.__setup_logger("api")
            self.logger_remote = self.__setup_logger("remote")

            BootAPI.__has_loaded   = True
            module_loader.load_modules()
            self._config         = config.Config(self)
            self.deserialize()

            self.authn = self.get_module_from_file(
                "authentication",
                "module",
                "authn_configfile"
            )
            self.authz  = self.get_module_from_file(
                "authorization",
                "module",
                "authz_allowall"
            )
            self.kickgen = kickgen.KickGen(self._config)
            self.logger.debug("API handle initialized")

    def __setup_logger(self,name):
        logger = logging.getLogger(name)
        logger.setLevel(logging.INFO)
        try:
            ch = logging.FileHandler("/var/log/cobbler/cobbler.log")
        except:
            raise CX(_("No write permissions on log file.  Are you root?")) 
        ch.setLevel(logging.INFO)
        formatter = logging.Formatter("%(asctime)s - %(name)s - %(message)s")
        ch.setFormatter(formatter)
        logger.addHandler(ch)
        return logger

    def log(self,msg,args=None,debug=False):
        if debug:
            logger = self.logger.debug
        else:
            logger = self.logger.info 
        if args is None:
            logger("%s" % msg)
        else:
            logger("%s; %s" % (msg, str(args)))

    def version(self):
        """
        What version is cobbler?
        Currently checks the RPM DB, which is not perfect.
        Will return "?" if not installed.
        """
        self.log("version")
        cmd = sub_process.Popen("/bin/rpm -q cobbler", stdout=sub_process.PIPE, shell=True)
        result = cmd.communicate()[0].replace("cobbler-","")
        if result.find("not installed") != -1:
            return "?"
        tokens = result[:result.rfind("-")].split(".")
        return int(tokens[0]) + 0.1 * int(tokens[1]) + 0.001 * int(tokens[2])

    def clear(self):
        """
        Forget about current list of profiles, distros, and systems
        """
        return self._config.clear()

    def __cmp(self,a,b):
        return cmp(a.name,b.name)

    def systems(self):
        """
        Return the current list of systems
        """
        return self._config.systems()

    def profiles(self):
        """
        Return the current list of profiles
        """
        return self._config.profiles()

    def distros(self):
        """
        Return the current list of distributions
        """
        return self._config.distros()

    def repos(self):
        """
        Return the current list of repos
        """
        return self._config.repos()

    def settings(self):
        """
        Return the application configuration
        """
        return self._config.settings()

    def copy_distro(self, ref, newname):
        self.log("copy_distro",[ref.name, newname])
        return self._config.distros().copy(ref,newname)

    def copy_profile(self, ref, newname):
        self.log("copy_profile",[ref.name, newname])
        return self._config.profiles().copy(ref,newname)

    def copy_system(self, ref, newname):
        self.log("copy_system",[ref.name, newname])
        return self._config.systems().copy(ref,newname)

    def copy_repo(self, ref, newname):
        self.log("copy_repo",[ref.name, newname])
        return self._config.repos().copy(ref,newname)

    def remove_distro(self, ref, recursive=False):
        self.log("remove_distro",[ref.name])
        return self._config.distros().remove(ref.name, recursive=recursive)

    def remove_profile(self,ref, recursive=False):
        self.log("remove_profile",[ref.name])
        return self._config.profiles().remove(ref.name, recursive=recursive)

    def remove_system(self,ref):
        self.log("remove_system",[ref.name])
        return self._config.systems().remove(ref.name)

    def remove_repo(self, ref):
        self.log("remove_repo",[ref.name])
        return self._config.repos().remove(ref.name)

    def rename_distro(self, ref, newname):
        self.log("rename_distro",[ref.name,newname])
        return self._config.distros().rename(ref,newname)

    def rename_profile(self, ref, newname):
        self.log("rename_profiles",[ref.name,newname])
        return self._config.profiles().rename(ref,newname)

    def rename_system(self, ref, newname):
        self.log("rename_system",[ref.name,newname])
        return self._config.systems().rename(ref,newname)

    def rename_repo(self, ref, newname):
        self.log("rename_repo",[ref.name,newname])
        return self._config.repos().rename(ref,newname)

    def new_distro(self,is_subobject=False):
        self.log("new_distro",[is_subobject])
        return self._config.new_distro(is_subobject=is_subobject)

    def new_profile(self,is_subobject=False):
        self.log("new_profile",[is_subobject])
        return self._config.new_profile(is_subobject=is_subobject)
    
    def new_system(self,is_subobject=False):
        self.log("new_system",[is_subobject])
        return self._config.new_system(is_subobject=is_subobject)

    def new_repo(self,is_subobject=False):
        self.log("new_repo",[is_subobject])
        return self._config.new_repo(is_subobject=is_subobject)

    def add_distro(self, ref, check_for_duplicate_names=False):
        self.log("add_distro",[ref.name])
        return self._config.distros().add(ref,save=True,check_for_duplicate_names=check_for_duplicate_names)

    def add_profile(self, ref, check_for_duplicate_names=False):
        self.log("add_profile",[ref.name])
        return self._config.profiles().add(ref,save=True,check_for_duplicate_names=check_for_duplicate_names)

    def add_system(self, ref, check_for_duplicate_names=False, check_for_duplicate_netinfo=False):
        self.log("add_system",[ref.name])
        return self._config.systems().add(ref,save=True,check_for_duplicate_names=check_for_duplicate_names,check_for_duplicate_netinfo=check_for_duplicate_netinfo)

    def add_repo(self, ref, check_for_duplicate_names=False):
        self.log("add_repo",[ref.name])
        return self._config.repos().add(ref,save=True,check_for_duplicate_names=check_for_duplicate_names)

    def find_distro(self, name=None, return_list=False, **kargs):
        return self._config.distros().find(name=name, return_list=return_list, **kargs)

    def find_profile(self, name=None, return_list=False, **kargs):
        return self._config.profiles().find(name=name, return_list=return_list, **kargs)

    def find_system(self, name=None, return_list=False, **kargs):
        return self._config.systems().find(name=name, return_list=return_list, **kargs)

    def find_repo(self, name=None, return_list=False, **kargs):
        return self._config.repos().find(name=name, return_list=return_list, **kargs)

    def auto_add_repos(self):
        """
        Import any repos this server knows about and mirror them.
        Credit: Seth Vidal.
        """
        self.log("auto_add_repos")
        try:
            import yum
        except:
            raise CX(_("yum is not installed"))

        version = yum.__version__
        (a,b,c) = version.split(".")
        version = a* 1000 + b*100 + c
        if version < 324:
            raise CX(_("need yum > 3.2.4 to proceed"))

        base = yum.YumBase()
        base.doRepoSetup()
        repos = base.repos.listEnabled()
        if len(repos) == 0:
            raise CX(_("no repos enabled/available -- giving up."))

        for repo in repos:
            url = repo.urls[0]
            cobbler_repo = self.new_repo()
            auto_name = repo.name.replace(" ","")
            # FIXME: probably doesn't work for yum-rhn-plugin ATM
            cobbler_repo.set_mirror(url)
            cobbler_repo.set_name(auto_name)
            print "auto adding: %s (%s)" % (auto_name, url)
            self._config.repos().add(cobbler_repo,save=True)

        # run cobbler reposync to apply changes
        return True 

    def generate_kickstart(self,profile,system):
        self.log("generate_kickstart")
        if system:
            return self.kickgen.generate_kickstart_for_system(system)
        else:
            return self.kickgen.generate_kickstart_for_profile(profile) 

    def check(self):
        """
        See if all preqs for network booting are valid.  This returns
        a list of strings containing instructions on things to correct.
        An empty list means there is nothing to correct, but that still
        doesn't mean there are configuration errors.  This is mainly useful
        for human admins, who may, for instance, forget to properly set up
        their TFTP servers for PXE, etc.
        """
        self.log("check")
        check = action_check.BootCheck(self._config)
        return check.run()

    def validateks(self):
        """
        Use ksvalidator (from pykickstart, if available) to determine
        whether the cobbler kickstarts are going to be (likely) well
        accepted by Anaconda.  Presence of an error does not indicate
        the kickstart is bad, only that the possibility exists.  ksvalidator
        is not available on all platforms and can not detect "future"
        kickstart format correctness.
        """
        self.log("validateks")
        validator = action_validate.Validate(self._config)
        return validator.run()

    def sync(self):
        """
        Take the values currently written to the configuration files in
        /etc, and /var, and build out the information tree found in
        /tftpboot.  Any operations done in the API that have not been
        saved with serialize() will NOT be synchronized with this command.
        """
        self.log("sync")
        sync = action_sync.BootSync(self._config)
        return sync.run()

    def reposync(self, name=None):
        """
        Take the contents of /var/lib/cobbler/repos and update them --
        or create the initial copy if no contents exist yet.
        """
        self.log("reposync",[name])
        reposync = action_reposync.RepoSync(self._config)
        return reposync.run(name)

    def status(self,mode):
        self.log("status")
        statusifier = action_status.BootStatusReport(self._config,mode)
        return statusifier.run()

    def import_tree(self,mirror_url,mirror_name,network_root=None,kickstart_file=None,rsync_flags=None,arch=None):
        """
        Automatically import a directory tree full of distribution files.
        mirror_url can be a string that represents a path, a user@host 
        syntax for SSH, or an rsync:// address.  If mirror_url is a 
        filesystem path and mirroring is not desired, set network_root 
        to something like "nfs://path/to/mirror_url/root" 
        """
        self.log("import_tree",[mirror_url, mirror_name, network_root, kickstart_file, rsync_flags])
        importer = action_import.Importer(
            self, self._config, mirror_url, mirror_name, network_root, kickstart_file, rsync_flags, arch
        )
        return importer.run()

    def serialize(self):
        """
        Save the config file(s) to disk.
        """
        self.log("serialize")
        return self._config.serialize()

    def deserialize(self):
        """
        Load the current configuration from config file(s)
        """
        return self._config.deserialize()

    def deserialize_raw(self,collection_name):
        """
        Get the collection back just as raw data.
        """
        return self._config.deserialize_raw(collection_name)

    def get_module_by_name(self,module_name):
        """
        Returns a loaded cobbler module named 'name', if one exists, else None.
        """
        return module_loader.get_module_by_name(module_name)

    def get_module_from_file(self,section,name,fallback=None):
        """
        Looks in /etc/cobbler/modules.conf for a section called 'section'
        and a key called 'name', and then returns the module that corresponds
        to the value of that key.
        """
        return module_loader.get_module_from_file(section,name,fallback)

    def get_modules_in_category(self,category):
        """
        Returns all modules in a given category, for instance "serializer", or "cli".
        """
        return module_loader.get_modules_in_category(category)

    def authenticate(self,user,password):
        """
        (Remote) access control.
        """
        rc = self.authn.authenticate(self,user,password)
        self.log("authenticate",[user,rc])
        return rc 

    def authorize(self,user,resource,arg1=None,arg2=None):
        """
        (Remote) access control.
        """
        rc = self.authz.authorize(self,user,resource,arg1,arg2)
        self.log("authorize",[user,resource,arg1,arg2,rc],debug=True)
        return rc