diff --git a/.hgignore b/.hgignore new file mode 100644 index 0000000..ba6778d --- /dev/null +++ b/.hgignore @@ -0,0 +1,3 @@ +\.py[oc]$ +dev.db$ +~$ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..5b6e7c6 --- /dev/null +++ b/LICENSE @@ -0,0 +1,340 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Library General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + 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, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Library General +Public License instead of this License. diff --git a/example/__init__.py b/example/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/example/manage.py b/example/manage.py new file mode 100755 index 0000000..6a3a879 --- /dev/null +++ b/example/manage.py @@ -0,0 +1,13 @@ +#!/usr/bin/env python +import sys, os +sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) +from django.core.management import execute_manager +try: + import settings # Assumed to be in the same directory. +except ImportError: + import sys + sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) + sys.exit(1) + +if __name__ == "__main__": + execute_manager(settings) diff --git a/example/settings.py b/example/settings.py new file mode 100644 index 0000000..5bf978c --- /dev/null +++ b/example/settings.py @@ -0,0 +1,93 @@ +# Django settings for example project. + +import os +PATH = os.path.dirname(os.path.abspath(__file__)) + +#DEBUG = False +DEBUG = True +TEMPLATE_DEBUG = DEBUG + +ADMINS = ( + # ('Your Name', 'your_email@domain.com'), + ('apollo13', 'apollo13@nodomain.org'), +) + +MANAGERS = ADMINS + +DATABASE_ENGINE = 'sqlite3' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. +DATABASE_NAME = 'dev.db' # Or path to database file if using sqlite3. +DATABASE_USER = '' # Not used with sqlite3. +DATABASE_PASSWORD = '' # Not used with sqlite3. +DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3. +DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. + +# Local time zone for this installation. Choices can be found here: +# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name +# although not all choices may be available on all operating systems. +# If running in a Windows environment this must be set to the same as your +# system time zone. +TIME_ZONE = 'America/Chicago' + +# Language code for this installation. All choices can be found here: +# http://www.i18nguy.com/unicode/language-identifiers.html +LANGUAGE_CODE = 'en-us' + +SITE_ID = 1 + +# If you set this to False, Django will make some optimizations so as not +# to load the internationalization machinery. +USE_I18N = True + +# Absolute path to the directory that holds media. +# Example: "/home/media/media.lawrence.com/" +MEDIA_ROOT = '' + +# URL that handles the media served from MEDIA_ROOT. Make sure to use a +# trailing slash if there is a path component (optional in other cases). +# Examples: "http://media.lawrence.com", "http://example.com/media/" +MEDIA_URL = '' + +# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a +# trailing slash. +# Examples: "http://foo.com/media/", "/media/". +ADMIN_MEDIA_PREFIX = '/media/' + +# Make this unique, and don't share it with anybody. +SECRET_KEY = 'm)mt5+(7xw-iltqmeu)mxt&e4#wu4svxf)l$d4zo*bu_$8=^=a' + +# List of callables that know how to import templates from various sources. +TEMPLATE_LOADERS = ( + 'django.template.loaders.filesystem.load_template_source', + 'django.template.loaders.app_directories.load_template_source', +# 'django.template.loaders.eggs.load_template_source', +) + +MIDDLEWARE_CLASSES = ( + 'django.middleware.common.CommonMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', +) + +ROOT_URLCONF = 'example.urls' + +TEMPLATE_DIRS = ( + # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". + # Always use forward slashes, even on Windows. + # Don't forget to use absolute paths, not relative paths. + PATH + '/templates', +) + +INSTALLED_APPS = ( + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.sites', + 'django.contrib.admin', + 'django.contrib.admindocs', + 'mountain.core', + 'mountain.monitor', + 'mountain.packages', +) + +EMAIL_HOST='localhost' +EMAIL_PORT=1025 diff --git a/example/templates/404.html b/example/templates/404.html new file mode 100644 index 0000000..731425a --- /dev/null +++ b/example/templates/404.html @@ -0,0 +1 @@ +404 - Not Found diff --git a/example/templates/500.html b/example/templates/500.html new file mode 100644 index 0000000..578a2c1 --- /dev/null +++ b/example/templates/500.html @@ -0,0 +1 @@ +Server Error diff --git a/example/urls.py b/example/urls.py new file mode 100644 index 0000000..f54c9a7 --- /dev/null +++ b/example/urls.py @@ -0,0 +1,17 @@ +from django.conf.urls.defaults import * + +# Uncomment the next two lines to enable the admin: +from django.contrib import admin +admin.autodiscover() + +import mountain.core.urls + +urlpatterns = patterns('', + # Example: + # (r'^example/', include('example.foo.urls')), + + (r'^admin/doc/', include('django.contrib.admindocs.urls')), + (r'^admin/', include(admin.site.urls)), + + (r'^', include(mountain.core.urls)) +) diff --git a/mountain/__init__.py b/mountain/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/mountain/core/__init__.py b/mountain/core/__init__.py new file mode 100644 index 0000000..a3a46d6 --- /dev/null +++ b/mountain/core/__init__.py @@ -0,0 +1,2 @@ +from mountain.core import registration + diff --git a/mountain/core/admin.py b/mountain/core/admin.py new file mode 100644 index 0000000..4a97e88 --- /dev/null +++ b/mountain/core/admin.py @@ -0,0 +1,36 @@ +from django.contrib import admin +from django.utils.simplejson import dumps + +from mountain.core.models import * +from mountain.core.utils import hash_types + +def force_resync(modeladmin, request, queryset): + for comp in queryset: + Message.objects.create(computer=comp, message=dumps({ + # TODO: Fix operation-id + 'type': 'resynchronize', 'operation-id': 1})) + +def confirm_computer(modeladmin, request, queryset): + queryset.update(confirmed=True) + for comp in queryset: + plugins = comp.company.activated_plugins.values_list('identifier', flat=True).order_by('identifier') + Message.objects.create(computer=comp, message=dumps({ + 'type': 'registration-done'})) + +class ComputerAdmin(admin.ModelAdmin): + actions = [force_resync, confirm_computer] + exclude = ('confirmed', 'client_accepted_types', 'client_accepted_types_hash') + +class CompanyAdmin(admin.ModelAdmin): + exclude = ('activated_plugins_hash',) + + def save_model(self, request, obj, form, change): + plugins = [i.identifier for i in form.cleaned_data['activated_plugins']] + plugins.sort() + obj.activated_plugins_hash = hash_types(plugins).encode('hex') + obj.save() + + +admin.site.register(Computer, ComputerAdmin) +admin.site.register(Company, CompanyAdmin) +admin.site.register(Message) diff --git a/mountain/core/management.py b/mountain/core/management.py new file mode 100644 index 0000000..37b5898 --- /dev/null +++ b/mountain/core/management.py @@ -0,0 +1,3 @@ +from mountain.core.utils import register_messagetype + +register_messagetype('register') diff --git a/mountain/core/models.py b/mountain/core/models.py new file mode 100644 index 0000000..7aa24c2 --- /dev/null +++ b/mountain/core/models.py @@ -0,0 +1,64 @@ +from django.db import models +from django.contrib.auth.models import User +from django.utils.translation import ugettext_lazy as _ + +class AcceptedTypes(models.Model): + """This models holds the message types which are supported by this server. + They are selectable through the company model, so each customer can + suppport different types (eg. not everyone needs a hardware inventory) + """ + identifier = models.CharField(max_length=255) + + def __unicode__(self): + return self.identifier + +class Company(models.Model): + """Company is used to define administrator and the activated plugins. + """ + verbose_name = models.CharField(_("verbose name"), max_length=255) + account_name = models.CharField(_("account name"), max_length=255, unique=True) + registration_password = models.CharField(_("registration password"), max_length=255) + administratos = models.ManyToManyField(User, verbose_name=_("administrators")) + activated_plugins = models.ManyToManyField(AcceptedTypes, verbose_name=_("activated plugins")) + activated_plugins_hash = models.CharField(max_length=255) + + def __unicode__(self): + return self.verbose_name + + class Meta: + verbose_name = _("Company") + verbose_name_plural = _("Companies") + +class Computer(models.Model): + """Represents one Computer, information is pulled from the client + registration request. Secure id is used to identify the computer, + if someone can sniff this id, he __will__ be able to connect as + this computer. + """ + company = models.ForeignKey(Company, verbose_name=_("company")) + computer_title = models.CharField(_("computer title"), max_length=255) + hostname = models.CharField(_("hostname"), max_length=255, unique=True) + # TODO: uniqness of secureid + secure_id = models.TextField(_("secure id")) + insecure_id = models.CharField(_("insecure id"), max_length=36, unique=True) + client_accepted_types = models.TextField() + client_accepted_types_hash = models.CharField(max_length=255) + confirmed = models.BooleanField(_("confirmed"), default=False) + + def __unicode__(self): + return self.computer_title + + class Meta: + verbose_name = _("Computer") + verbose_name_plural = _("Computers") + +class Message(models.Model): + """Message which is queued and should get send to the client""" + computer = models.ForeignKey(Computer, verbose_name=_("computer")) + message = models.TextField(_("message"), help_text=_("JSON encoded")) + + class Meta: + verbose_name = _("Message") + verbose_name_plural = _("Messages") + + diff --git a/mountain/core/registration.py b/mountain/core/registration.py new file mode 100644 index 0000000..bfbe24e --- /dev/null +++ b/mountain/core/registration.py @@ -0,0 +1,35 @@ +import uuid, string +from random import choice + +from django.utils.simplejson import dumps + +from mountain.core.models import Computer, Company +from mountain.core.signals import message_available +from mountain.core.utils import MessageType, hash_types + +CHARS = string.ascii_letters + string.digits + string.punctuation + +def handle_registration(sender, computer, request_data, msg_data, **kwargs): + try: + company = Company.objects.get(account_name=msg_data['account_name']) + except Company.DoesNotExist: + return [{'type':'registration', 'info':'unknown-account'}] + + if msg_data['registration_password'] != company.registration_password: + return [{'type':'registration', 'info':'unknown-account'}] + + comp,created = Computer.objects.get_or_create( + hostname=msg_data['hostname'], company=company) + comp.computer_title=msg_data['computer_title'] + comp.secure_id= ''.join([choice(CHARS) for i in range(1600)]) + comp.insecure_id=str(uuid.uuid4()) + # TODO: this is only set on registration, but we need to check if the client changed them + comp.client_accepted_types = dumps(request_data['client-accepted-types']) + comp.client_accepted_types_hash = hash_types(request_data['client-accepted-types']).encode('hex') + comp.save() + + + return [{'type':'set-id', 'id':comp.secure_id, + 'insecure-id':comp.insecure_id}] + +message_available.connect(handle_registration, sender=MessageType("register")) diff --git a/mountain/core/settings.py b/mountain/core/settings.py new file mode 100644 index 0000000..2f90422 --- /dev/null +++ b/mountain/core/settings.py @@ -0,0 +1,2 @@ +# generate one with uuid.uuid1() and move into global settings.py +SERVER_UUID = 'ecd4be8b-2de9-11de-9cd3-0018f3cfc4db' diff --git a/mountain/core/signals.py b/mountain/core/signals.py new file mode 100644 index 0000000..e5911ec --- /dev/null +++ b/mountain/core/signals.py @@ -0,0 +1,3 @@ +import django.dispatch + +message_available = django.dispatch.Signal(providing_args=['computer', 'request_data', 'msg_data']) diff --git a/mountain/core/urls.py b/mountain/core/urls.py new file mode 100644 index 0000000..5f37ef2 --- /dev/null +++ b/mountain/core/urls.py @@ -0,0 +1,8 @@ +from django.conf.urls.defaults import * + +from views import message_system, ping + +urlpatterns = patterns('', + (r'message-system/?$', message_system), + (r'ping/?$', ping), +) diff --git a/mountain/core/utils.py b/mountain/core/utils.py new file mode 100644 index 0000000..1a35ecf --- /dev/null +++ b/mountain/core/utils.py @@ -0,0 +1,45 @@ +from hashlib import md5 + +from landscape.lib.bpickle import dumps + +from django.http import HttpResponse + +from mountain.core.settings import SERVER_UUID +from mountain.core.models import AcceptedTypes + +def render_messages(messages, computer=None, append_uuid=True): + """Updates the answer with the server-uuid, pickles it and returns the + HttpReponse. + """ + ret = {'messages': messages} + if append_uuid: + ret.update({'server-uuid': SERVER_UUID}) + if computer: + ret.update({'client-accepted-types-hash': computer.client_accepted_types_hash.decode('hex')}) + return HttpResponse(dumps(ret)) + +def MessageType(type, __instance_cache={}): + """Use this to register your receiver function to a string. + """ + instance = __instance_cache.setdefault(type, object()) + return instance + +def hash_types(types): + """The client only sends the hashed server types, we do the same, + compare them and only send new types if the types difer. + """ + m = md5() + m.update(";".join(types)) + return m.digest() + +def register_messagetype(type): + from django.db.models.signals import post_syncdb + from mountain.core import models + + def install_type(sender, app, created_models, verbosity=0, **kwargs): + if verbosity>=1: + print "Installing message type %s" % type + AcceptedTypes.objects.get_or_create(identifier=type) + + post_syncdb.connect(install_type, sender=models, weak=False) + diff --git a/mountain/core/views.py b/mountain/core/views.py new file mode 100644 index 0000000..560b455 --- /dev/null +++ b/mountain/core/views.py @@ -0,0 +1,66 @@ +# -*- coding: utf-8 -*- +from django.utils import simplejson + +from landscape.lib.bpickle import loads + +from mountain.core.models import Computer, Message +from mountain.core.utils import render_messages, MessageType, hash_types +from mountain.core.signals import message_available + +def ping(request): + id = request.POST.get('insecure_id') + msg_count = Message.objects.filter(computer__insecure_id=id).count() + return render_messages(bool(msg_count), append_uuid=False) + +def message_system(request): + try: + secure_id = request.META.get('HTTP_X_COMPUTER_ID') + data = loads(request.raw_post_data) + received_msgs = data.pop('messages', []) + return_msgs = [] + + computer = company = None + # Get company and computer objects if we do have a secure_id + if secure_id: + try: + computer = Computer.objects.get(secure_id=secure_id) + company = computer.company + except Computer.DoesNotExist: + return render_messages({'type':'unkown-id'}) + + # Special case registration, as we get a request with nothing, + # and without accepting register, we'll never get a registration. + if company: + accepted_types = company.activated_plugins.values_list('identifier', flat=True).order_by('identifier') + accepted_types_hash = company.activated_plugins_hash.decode('hex') + else: + accepted_types = ['register'] + accepted_types_hash = hash_types(['register']) + + # Determine whether we need to notify the client about new/delete types + if data.get('accepted-types') != accepted_types_hash: + return_msgs.append({'type':'accepted-types', 'types':list(accepted_types)}) + + for msg in received_msgs: + ret_ = message_available.send(sender=MessageType(msg['type']), + computer=computer, + request_data=data, msg_data=msg) + ret_ = map(lambda x: x[1], ret_) + ret = [] + for i in ret_: + ret.extend(i if isinstance(i, (tuple,list)) else list(i)) + return_msgs.extend(ret) + + query = Message.objects.filter(computer=computer) + if computer and query.count(): + messages = query + for msg in messages: + return_msgs.append(simplejson.loads(msg.message)) + query.delete() + + except Exception,e: + import sys, traceback + traceback.print_exception(*sys.exc_info()) + raise e + + return render_messages(return_msgs, computer=computer) diff --git a/mountain/monitor/__init__.py b/mountain/monitor/__init__.py new file mode 100644 index 0000000..75de8de --- /dev/null +++ b/mountain/monitor/__init__.py @@ -0,0 +1,2 @@ +#from mountain.monitor import processorinfo, hardwareinventory +from mountain.monitor import computerinfo diff --git a/mountain/monitor/admin.py b/mountain/monitor/admin.py new file mode 100644 index 0000000..2a1403d --- /dev/null +++ b/mountain/monitor/admin.py @@ -0,0 +1,18 @@ +from django.contrib import admin + +from mountain.monitor.models import ProcessorInfo, HardwarePart, ComputerInfo + +class ProcessorInfoAdmin(admin.ModelAdmin): + list_display = ('model', 'vendor', 'processor_id', 'cache_size', 'computer') + list_filter = ('computer',) + +class HardwarePartAdmin(admin.ModelAdmin): + list_display = ('product', 'vendor', 'computer') + list_filter = ('computer',) + +class ComputerInfoAdmin(admin.ModelAdmin): + list_display = ('hostname', 'code_name', 'description', 'distributor_id', 'release', 'computer') + +#admin.site.register(ProcessorInfo, ProcessorInfoAdmin) +#admin.site.register(HardwarePart, HardwarePartAdmin) +admin.site.register(ComputerInfo, ComputerInfoAdmin) diff --git a/mountain/monitor/computerinfo.py b/mountain/monitor/computerinfo.py new file mode 100644 index 0000000..b83b099 --- /dev/null +++ b/mountain/monitor/computerinfo.py @@ -0,0 +1,19 @@ +from mountain.core.signals import message_available +from mountain.core.utils import MessageType, register_messagetype +from mountain.monitor.models import ComputerInfo + +def handle_computer_info(sender, computer, request_data, msg_data, **kwargs): + comp_info, created = ComputerInfo.objects.get_or_create(computer=computer) + comp_info.hostname = msg_data['hostname'] + comp_info.save() + return [] + +def handle_distribution_info(sender, computer, request_data, msg_data, **kwargs): + dist_info, created = ComputerInfo.objects.get_or_create(computer=computer) + for i in ['code-name', 'description', 'distributor-id', 'release'] : + setattr(dist_info, i.replace('-','_'), msg_data[i]) + dist_info.save() + return [] + +message_available.connect(handle_computer_info, sender=MessageType('computer-info')) +message_available.connect(handle_distribution_info, sender=MessageType('distribution-info')) diff --git a/mountain/monitor/management.py b/mountain/monitor/management.py new file mode 100644 index 0000000..ec50395 --- /dev/null +++ b/mountain/monitor/management.py @@ -0,0 +1,5 @@ +from mountain.core.utils import register_messagetype + +register_messagetype('computer-info') +register_messagetype('distribution-info') +register_messagetype('processor-info') diff --git a/mountain/monitor/models.py b/mountain/monitor/models.py new file mode 100644 index 0000000..5e6bb75 --- /dev/null +++ b/mountain/monitor/models.py @@ -0,0 +1,33 @@ +from django.db import models + +from mountain.core.models import Computer + +class ProcessorInfo(models.Model): + computer = models.ForeignKey(Computer) + processor_id = models.SmallIntegerField() + model = models.CharField(max_length=255) + + vendor = models.CharField(max_length=255, default='') + cache_size = models.SmallIntegerField(null=True) + + def __unicode__(self): + return self.model + +class HardwarePart(models.Model): + computer = models.ForeignKey(Computer) + udi = models.CharField(max_length=255) + product = models.CharField(max_length=255) + vendor = models.CharField(max_length=255, default='') + driver = models.CharField(max_length=255, default='') + subsystem = models.CharField(max_length=255, default='') + + def __unicode__(self): + return self.product + +class ComputerInfo(models.Model): + computer = models.ForeignKey(Computer) + hostname = models.CharField(max_length=255) + code_name = models.CharField(max_length=255) + description = models.CharField(max_length=255) + distributor_id = models.CharField(max_length=255) + release = models.CharField(max_length=255) diff --git a/mountain/monitor/processorinfo.py b/mountain/monitor/processorinfo.py new file mode 100644 index 0000000..50bb39d --- /dev/null +++ b/mountain/monitor/processorinfo.py @@ -0,0 +1,18 @@ +from mountain.core.signals import message_available +from mountain.core.utils import MessageType +from mountain.monitor.models import ProcessorInfo + +def handle_proc_info(sender, computer, request_data, msg_data, **kwargs): + ProcessorInfo.objects.filter(computer=computer).delete() + for p in msg_data['processors']: + p_info = ProcessorInfo(computer=computer, processor_id=p['processor-id'], + model=p['model']) + for i in ['cache-size', 'vendor']: + if p.get(i): + setattr(p_info, i.replace('-','_'), p.get(i)) + + p_info.save() + + return [] + +message_available.connect(handle_proc_info, sender=MessageType('processor-info')) diff --git a/mountain/packages/__init__.py b/mountain/packages/__init__.py new file mode 100644 index 0000000..4837a7b --- /dev/null +++ b/mountain/packages/__init__.py @@ -0,0 +1 @@ +from . import packages diff --git a/mountain/packages/admin.py b/mountain/packages/admin.py new file mode 100644 index 0000000..6113cba --- /dev/null +++ b/mountain/packages/admin.py @@ -0,0 +1,11 @@ +from django.contrib import admin + +from mountain.packages.models import * + +class PackageAdmin(admin.ModelAdmin): + list_display = ('name', 'summary', 'section', 'type') + list_filter = ('section',) + ordering = ('name',) + search_fields = ('name',) + +admin.site.register(PackageHash, PackageAdmin) diff --git a/mountain/packages/management.py b/mountain/packages/management.py new file mode 100644 index 0000000..0599ace --- /dev/null +++ b/mountain/packages/management.py @@ -0,0 +1,5 @@ +from mountain.core.utils import register_messagetype + +register_messagetype('unknown-package-hashes') +register_messagetype('packages') +register_messagetype('add-packages') diff --git a/mountain/packages/models.py b/mountain/packages/models.py new file mode 100644 index 0000000..ff40d5a --- /dev/null +++ b/mountain/packages/models.py @@ -0,0 +1,25 @@ +from django.db import models + +from mountain.core.models import Computer + +class PackageHashManager(models.Manager): + def hashes_in_bulk(self, id_list): + qs = self.model.objects.filter(hash__in=id_list) + return dict([(obj.hash, obj) for obj in qs.iterator()]) + +class PackageHash(models.Model): + hash = models.CharField(max_length=40, db_index=True, unique=True) + name = models.CharField(max_length=255) + summary = models.CharField(max_length=255) + version = models.CharField(max_length=255) + description = models.TextField() + installed_size = models.IntegerField(null=True) + size = models.IntegerField() + type = models.IntegerField() + section = models.CharField(max_length=255) + + objects = PackageHashManager() + + class Meta: + verbose_name = "Package hash" + verbose_name_plural = "Package hashes" diff --git a/mountain/packages/packages.py b/mountain/packages/packages.py new file mode 100644 index 0000000..a829e42 --- /dev/null +++ b/mountain/packages/packages.py @@ -0,0 +1,31 @@ +from mountain.core.signals import message_available +from mountain.core.utils import MessageType +from mountain.packages.models import PackageHash +from mountain.packages.utils import get_hash + +def handle_unknown_hashes(sender, computer, request_data, msg_data, **kwargs): + hashes = [i.encode('hex') for i in msg_data['hashes']] + data = PackageHash.objects.hashes_in_bulk(hashes) + ids = [(data.get(hash).id if data.get(hash) else None) for hash in hashes] + return [{'type': 'package-ids', 'ids':ids, 'request-id':msg_data['request-id']}] + +def handle_add_packages(sender, computer, request_data, msg_data, **kwargs): + ids = [] + for p in msg_data['packages']: + hash = get_hash(p['type'], p['name'], p['version'], p['relations']) + m = PackageHash(hash = hash) + for i in ('name', 'summary', 'version', 'description', + 'installed-size', 'size', 'type', 'section'): + setattr(m, i.replace('-', '_'), p.get(i)) + # TODO: that's ugly + try: + m.save() + ids.append(m.id) + except Exception, e: + print p + print e + + return [{'type': 'package-ids', 'ids':ids, 'request-id':msg_data['request-id']}] + +message_available.connect(handle_unknown_hashes, sender=MessageType("unknown-package-hashes")) +message_available.connect(handle_add_packages, sender=MessageType("add-packages")) diff --git a/mountain/packages/tests.py b/mountain/packages/tests.py new file mode 100644 index 0000000..2247054 --- /dev/null +++ b/mountain/packages/tests.py @@ -0,0 +1,23 @@ +""" +This file demonstrates two different styles of tests (one doctest and one +unittest). These will both pass when you run "manage.py test". + +Replace these with more appropriate tests for your application. +""" + +from django.test import TestCase + +class SimpleTest(TestCase): + def test_basic_addition(self): + """ + Tests that 1 + 1 always equals 2. + """ + self.failUnlessEqual(1 + 1, 2) + +__test__ = {"doctest": """ +Another way to test that 1 + 1 is equal to 2. + +>>> 1 + 1 == 2 +True +"""} + diff --git a/mountain/packages/utils.py b/mountain/packages/utils.py new file mode 100644 index 0000000..e9ad288 --- /dev/null +++ b/mountain/packages/utils.py @@ -0,0 +1,8 @@ +from hashlib import sha1 + +def get_hash(type, name, version, relations): + digest = sha1("[%d %s %s]" % (type, name, version)) + relations.sort() + for pair in relations: + digest.update("[%d %s]" % pair) + return digest.hexdigest() diff --git a/mountain/packages/views.py b/mountain/packages/views.py new file mode 100644 index 0000000..60f00ef --- /dev/null +++ b/mountain/packages/views.py @@ -0,0 +1 @@ +# Create your views here.