Example #1
0
from datetime import datetime, timezone, timedelta

from django.db import models
from django.core.exceptions import ValidationError

from cinp.orm_django import DjangoCInP as CInP

from contractor.Building.models import Foundation, Structure
from contractor.fields import MapField

MAX_BOX_LIFE = 96  # in hours
cinp = CInP('PostOffice', '0.1')


class PostOfficeException(ValueError):
    def __init__(self, code, message):
        super().__init__(message)
        self.message = message
        self.code = code

    @property
    def response_data(self):
        return {
            'class': 'PostOfficeException',
            'error': self.code,
            'message': self.message
        }

    def __str__(self):
        return 'PostOfficeException ({0}): {1}'.format(self.code, self.message)
Example #2
0
from django.db import models
from django.db.models.signals import post_save, post_delete
from django.core.exceptions import ValidationError

from cinp.orm_django import DjangoCInP as CInP

from contractor.fields import MapField, StringListField, name_regex, config_name_regex
from contractor.tscript import parser
from contractor.lib.config import getConfig
from contractor.BluePrint.lib import validateTemplate
from contractor.Records.lib import post_save_callback, post_delete_callback

cinp = CInP('BluePrint', '0.1')


class BluePrintException(ValueError):
    def __init__(self, code, message):
        super().__init__(message)
        self.message = message
        self.code = code

    @property
    def response_data(self):
        return {
            'class': 'BluePrintException',
            'error': self.code,
            'message': self.message
        }

    def __str__(self):
        return 'BluePrintException ({0}): {1}'.format(self.code, self.message)
Example #3
0
import re
from django.db import models
from django.core.exceptions import ValidationError, ObjectDoesNotExist

from cinp.orm_django import DjangoCInP as CInP

from contractor.fields import MapField, IpAddressField, hostname_regex, name_regex
from contractor.BluePrint.models import PXE
from contractor.Site.models import Site
from contractor.lib.ip import IpIsV4, CIDRNetworkBounds, StrToIp, IpToStr, CIDRNetworkSize, CIDRNetmask

cinp = CInP('Utilities', '0.1')


def ipAddress2Native(ip_address):
    try:
        address_block = AddressBlock.objects.get(subnet__lte=ip_address,
                                                 _max_address__gte=ip_address)
    except AddressBlock.DoesNotExist:
        raise ValueError(
            'ip_address "{0}" does not exist in any existing Address Blocks'.
            format(ip_address))

    return address_block, StrToIp(ip_address) - StrToIp(address_block.subnet)


@cinp.model()
class Networked(models.Model):
    hostname = models.CharField(max_length=100)
    site = models.ForeignKey(Site, on_delete=models.PROTECT)
Example #4
0
from cinp.orm_django import DjangoCInP as CInP

from contractor.Utilities.models import AddressBlock
from contractor.Foreman.lib import processJobs, jobResults, jobError

cinp = CInP('SubContractor', '0.1')


# these are only for subcontractor to talk to, thus some of the job_id short cuts
@cinp.staticModel()  # TODO: move to  Foreman?
class Dispatch():
    def __init__(self):
        super().__init__()

    @cinp.action(return_type={
        'type': 'Map',
        'is_array': True
    },
                 paramater_type_list=[{
                     'type': 'Model',
                     'model': 'contractor.Site.models.Site'
                 }, {
                     'type': 'String',
                     'is_array': True
                 }, 'Integer'])
    @staticmethod
    def getJobs(site, module_list, max_jobs=10):
        result = processJobs(site, module_list, max_jobs)
        print('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> "{0}"'.format(result))
        return result
Example #5
0
from django.db import models
from django.core.exceptions import ValidationError

from cinp.orm_django import DjangoCInP as CInP

from contractor.Site.models import Site
from contractor.Building.models import Foundation, Complex, FOUNDATION_SUBCLASS_LIST, COMPLEX_SUBCLASS_LIST
from contractor.BluePrint.models import FoundationBluePrint

from contractor_plugins.Manual.module import set_power, power_state, wait_for_poweroff

cinp = CInP('Manual', '0.1')

FOUNDATION_SUBCLASS_LIST.append('manualfoundation')
FOUNDATION_SUBCLASS_LIST.append('manualcomplexedfoundation')
COMPLEX_SUBCLASS_LIST.append('manualcomplex')


@cinp.model(property_list=('state', 'type'))
class ManualComplex(Complex):
    @property
    def subclass(self):
        return self

    @property
    def type(self):
        return 'Manual'

    def newFoundation(self, hostname, site):
        foundation = ManualComplexedFoundation(
            site=site,
Example #6
0
from django.db import models
from django.db.models import Q
from django.db.models.signals import post_save, post_delete
from django.core.exceptions import ValidationError

from cinp.orm_django import DjangoCInP as CInP

from contractor.fields import MapField, name_regex, config_name_regex
from contractor.lib.config import getConfig
from contractor.Records.lib import post_save_callback, post_delete_callback
from contractor.Directory.models import Zone

# this is the what we want implemented, ie where, how it's grouped and waht is in thoes sites/groups, the logical aspect

cinp = CInP( 'Site', '0.1' )


class SiteException( ValueError ):
  def __init__( self, code, message ):
    super().__init__( message )
    self.message = message
    self.code = code

  @property
  def response_data( self ):
    return { 'class': 'SiteException', 'error': self.code, 'message': self.message }

  def __str__( self ):
    return 'SiteException ({0}): {1}'.format( self.code, self.message )

Example #7
0
from django.db import models
from django.core.exceptions import ValidationError

from cinp.orm_django import DjangoCInP as CInP

from contractor.Site.models import Site
from contractor.Building.models import Foundation, FOUNDATION_SUBCLASS_LIST
from contractor.Survey.models import Plot
# from contractor.Utilities.models import RealNetworkInterface, Networked
from contractor.Foreman.lib import RUNNER_MODULE_LIST

from contractor_plugins.AMT.module import set_power, power_state, wait_for_poweroff

cinp = CInP('AMT', '0.1')

FOUNDATION_SUBCLASS_LIST.append('amtfoundation')
RUNNER_MODULE_LIST.append('contractor_plugins.AMT.module')


@cinp.model(property_list=('state', 'type', 'class_list'))
class AMTFoundation(Foundation):  # , Networked ):
    amt_username = models.CharField(max_length=16, default='admin')
    amt_password = models.CharField(max_length=16)
    # amt_interface = models.ForeignKey( RealNetworkInterface )
    amt_ip_address = models.CharField(max_length=30)
    plot = models.ForeignKey(Plot)

    @staticmethod
    def getTscriptValues(write_mode=False):  # locator is handled seperatly
        result = super(AMTFoundation,
                       AMTFoundation).getTscriptValues(write_mode)
Example #8
0
import re
from django.db import models
from django.core.exceptions import ValidationError

from cinp.orm_django import DjangoCInP as CInP

from contractor.Site.models import Site
from contractor.Building.models import Foundation, Complex, Structure, FOUNDATION_SUBCLASS_LIST, COMPLEX_SUBCLASS_LIST
from contractor.Foreman.lib import RUNNER_MODULE_LIST
from contractor.BluePrint.models import FoundationBluePrint
from contractor.lib.config import getConfig, mergeValues

from contractor_plugins.VCenter.module import set_power, power_state, wait_for_poweroff, destroy, get_interface_map, set_interface_macs, execute, mark_as_template, export

cinp = CInP('VCenter', '0.1')

FOUNDATION_SUBCLASS_LIST.append('vcenterfoundation')
COMPLEX_SUBCLASS_LIST.append('vcentercomplex')
RUNNER_MODULE_LIST.append('contractor_plugins.VCenter.module')

datacenter_name_regex = re.compile('^[a-zA-Z0-9][a-zA-Z0-9_\-]*$')
cluster_name_regex = re.compile('^[a-zA-Z0-9][a-zA-Z0-9_\-\.]*$')


@cinp.model(property_list=('state', 'type'))
class VCenterComplex(Complex):
    vcenter_host = models.ForeignKey(
        Structure,
        help_text=
        'set to VCenter or the ESX host, if ESX host, leave members empty'
    )  # no need for unique, the same vcenter_host can be used for multiple clusters
Example #9
0
import re
from django.db import models
from django.core.exceptions import ValidationError

from cinp.orm_django import DjangoCInP as CInP

from contractor.Building.models import Foundation, Complex, Structure, FOUNDATION_SUBCLASS_LIST, COMPLEX_SUBCLASS_LIST, FoundationNetworkInterface
from contractor.Foreman.lib import RUNNER_MODULE_LIST
from contractor.Utilities.models import RealNetworkInterface
from contractor.BluePrint.models import FoundationBluePrint

from contractor_plugins.Vcenter.module import set_power, power_state, wait_for_poweroff, destroy, get_interface_map, set_interface_macs

cinp = CInP('Vcenter', '0.1')

FOUNDATION_SUBCLASS_LIST.append('vcenterfoundation')
COMPLEX_SUBCLASS_LIST.append('vcentercomplex')
RUNNER_MODULE_LIST.append('contractor_plugins.Vcenter.module')

datacenter_name_regex = re.compile('^[a-zA-Z0-9][a-zA-Z0-9_\-]*$')
cluster_name_regex = re.compile('^[a-zA-Z0-9][a-zA-Z0-9_\-\.]*$')


@cinp.model(property_list=('state', 'type'))
class VcenterComplex(Complex):
    vcenter_host = models.ForeignKey(
        Structure,
        help_text=
        'set to VCenter or the ESX host, if ESX host, leave members empty'
    )  # no need for unique, the same vcenter_host can be used for multiple clusters
    vcenter_username = models.CharField(max_length=50)
Example #10
0
from django.db import models

from cinp.orm_django import DjangoCInP as CInP

from contractor.Building.models import Foundation, FOUNDATION_SUBCLASS_LIST
from contractor.Foreman.lib import RUNNER_MODULE_LIST

from contractor_plugins.VirtualBox.module import set_power, power_state, wait_for_poweroff, destroy, set_interface_macs

cinp = CInP('VirtualBox', '0.1')

FOUNDATION_SUBCLASS_LIST.append('virtualboxfoundation')
RUNNER_MODULE_LIST.append('contractor_plugins.VirtualBox.module')


@cinp.model(property_list=('state', 'type', 'class_list'))
class VirtualBoxFoundation(Foundation):
    virtualbox_uuid = models.CharField(
        max_length=36, blank=True, null=True
    )  # not going to do unique, there could be lots of virtualbox hosts

    @staticmethod
    def getTscriptValues(write_mode=False):  # locator is handled seperatly
        result = super(VirtualBoxFoundation,
                       VirtualBoxFoundation).getTscriptValues(write_mode)

        result['virtualbox_uuid'] = (
            lambda foundation: foundation.virtualbox_uuid, None)

        if write_mode is True:
            result['virtualbox_uuid'] = (
Example #11
0
import pickle

from django.db import models
from django.core.exceptions import ValidationError, ObjectDoesNotExist

from cinp.orm_django import DjangoCInP as CInP

from contractor.fields import JSONField
from contractor.Site.models import Site
from contractor.Building.models import Foundation, Structure, Dependancy

# stuff for getting handeling tasks, everything here should be ephemerial, only things that are in progress/flight

cinp = CInP('Foreman', '0.1')


@cinp.model(not_allowed_method_list=[
    'LIST', 'GET', 'CREATE', 'UPDATE', 'DELETE', 'CALL'
],
            hide_field_list=('script_runner', ),
            property_list=('progress', ))
class BaseJob(models.Model):
    JOB_STATE_CHOICES = (('queued', 'queued'), ('waiting', 'waiting'),
                         ('done', 'done'), ('paused', 'paused'),
                         ('error', 'error'), ('aborted', 'aborted'))
    site = models.ForeignKey(Site, editable=False, on_delete=models.CASCADE)
    state = models.CharField(max_length=10, choices=JOB_STATE_CHOICES)
    status = JSONField(default=[], blank=True)
    message = models.CharField(max_length=1024, default='', blank=True)
    script_runner = models.BinaryField(editable=False)
    script_name = models.CharField(max_length=40,
Example #12
0
from django.db.models import Q
from django.db.models.signals import post_save, post_delete
from django.core.exceptions import ValidationError, ObjectDoesNotExist

from cinp.orm_django import DjangoCInP as CInP

from contractor.fields import MapField, JSONField, name_regex, config_name_regex
from contractor.Site.models import Site
from contractor.BluePrint.models import StructureBluePrint, FoundationBluePrint
from contractor.Utilities.models import Networked, RealNetworkInterface
from contractor.lib.config import getConfig, mergeValues
from contractor.Records.lib import post_save_callback, post_delete_callback

# this is where the plan meets the resources to make it happen, the actuall impelemented thing, and these represent things, you can't delete the records without cleaning up what ever they are pointing too

cinp = CInP( 'Building', '0.1' )

FOUNDATION_SUBCLASS_LIST = []
COMPLEX_SUBCLASS_LIST = []


class BuildingException( ValueError ):
  def __init__( self, code, message ):
    super().__init__( message )
    self.message = message
    self.code = code

  @property
  def response_data( self ):
    return { 'class': 'BuildingException', 'error': self.code, 'message': self.message }
Example #13
0
import hashlib
from datetime import datetime, timezone

from django.core.exceptions import ValidationError
from django.db import models
from django.db.models.signals import pre_delete

from cinp.orm_django import DjangoCInP as CInP
from cinp.server_common import NotAuthorized

from packrat.Attrib.models import Tag, DistroVersion
from packrat.Repo.models import Repo
from packrat.lib.info import infoDetect
from packrat.fields import name_regex, filename_regex, USERNAME_LENGTH, FILE_VERSION_LENGTH, FILE_ARCH_CHOICES, FILE_TYPE_LENGTH, FILE_ARCH_LENGTH

cinp = CInP( 'Package', '2.0' )


class PackageException( ValueError ):
  def __init__( self, code, message ):
    super().__init__( message )
    self.message = message
    self.code = code

  @property
  def response_data( self ):
    return { 'exception': 'PackageException', 'error': self.code, 'message': self.message }

  def __str__( self ):
    return 'PackageException ({0}): {1}'.format( self.code, self.message )
Example #14
0
"""

from django.db import models
from django.core.exceptions import ValidationError

from cinp.orm_django import DjangoCInP as CInP

from contractor.Site.models import Site
from contractor.Building.models import Foundation, Complex, FOUNDATION_SUBCLASS_LIST, COMPLEX_SUBCLASS_LIST
from contractor.BluePrint.models import FoundationBluePrint
from contractor.lib.config import getConfig, mergeValues
from contractor.Foreman.lib import RUNNER_MODULE_LIST

from contractor_plugins.VirtualBox.module import set_power, power_state, wait_for_poweroff, destroy, get_interface_map, set_interface_macs

cinp = CInP('VirtualBox', '0.1', __doc__)

FOUNDATION_SUBCLASS_LIST.append('virtualboxfoundation')
COMPLEX_SUBCLASS_LIST.append('virtualboxcomplex')
RUNNER_MODULE_LIST.append('contractor_plugins.VirtualBox.module')


@cinp.model(property_list=('state', 'type'))
class VirtualBoxComplex(Complex):
    """
  Complex for VirtualBox.  Only one member is allowed.  The ip address
  for managing the VirtualBox instance comes from the member's primary ip.
  """
    virtualbox_username = models.CharField(max_length=50)
    virtualbox_password = models.CharField(max_length=50)
Example #15
0
from django.db import models

from cinp.orm_django import DjangoCInP as CInP

from contractor.Site.models import Site
from contractor.Building.models import Foundation, FOUNDATION_SUBCLASS_LIST
from contractor.Foreman.lib import RUNNER_MODULE_LIST

from contractor_plugins.AWS.module import set_power, power_state, destroy, set_interface_macs, set_ip_addresses

cinp = CInP('AWS', '0.1')

FOUNDATION_SUBCLASS_LIST.append('awsec2foundation')
RUNNER_MODULE_LIST.append('contractor_plugins.AWS.module')


@cinp.model(property_list=('state', 'type', 'class_list'))
class AWSEC2Foundation(Foundation):
    awsec2_instance_id = models.CharField(
        max_length=19, blank=True, null=True
    )  # not going to do unique, there could be multiple AWS accounts

    @staticmethod
    def getTscriptValues(write_mode=False):  # locator is handled seperatly
        result = super(AWSEC2Foundation,
                       AWSEC2Foundation).getTscriptValues(write_mode)

        result['awsec2_instance_id'] = (
            lambda foundation: foundation.awsec2_instance_id, None)

        if write_mode is True:
Example #16
0
File: models.py Project: cinp/demo
from django.db import models

from cinp.orm_django import DjangoCInP as CInP
# from django.contrib.auth.models import User

cinp = CInP('Car', '0.1', 'Cars and their Models')


@cinp.model(property_list=[], not_allowed_verb_list=[])
class Model(models.Model):
    """
All the Make/Model/Years for the cars
  """
    make = models.CharField(max_length=100)
    model = models.CharField(max_length=100)
    year = models.IntegerField()
    description = models.CharField(max_length=200)
    updated = models.DateTimeField(editable=False, auto_now=True)
    created = models.DateTimeField(editable=False, auto_now_add=True)

    @cinp.list_filter(name='make', paramater_type_list=['String'])
    @staticmethod
    def filter_make(make):
        return Model.objects.filter(make=make)

    @cinp.list_query_filter(field_list=[{
        'name': 'make',
        'type': 'String'
    }, {
        'name': 'model',
        'type': 'String'
Example #17
0
import re
from django.db import models
from django.core.exceptions import ValidationError

from cinp.orm_django import DjangoCInP as CInP

from contractor.Site.models import Site
from contractor.Building.models import Foundation, Complex, FOUNDATION_SUBCLASS_LIST, COMPLEX_SUBCLASS_LIST
from contractor.Foreman.lib import RUNNER_MODULE_LIST
from contractor.BluePrint.models import FoundationBluePrint
from contractor.lib.config import getConfig, mergeValues

from contractor_plugins.Azure.module import set_power, power_state, destroy

cinp = CInP('Azure', '0.1')

FOUNDATION_SUBCLASS_LIST.append('azurefoundation')
COMPLEX_SUBCLASS_LIST.append('azurecomplex')
RUNNER_MODULE_LIST.append('contractor_plugins.Azure.module')

uuid_regex = re.compile(
    '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$')
resource_group_regex = re.compile(
    '^[-\w\._\(\)]+$'
)  # from https://docs.microsoft.com/en-us/rest/api/resources/resourcegroups/createorupdate


@cinp.model(property_list=('state', 'type'))
class AzureComplex(Complex):
    azure_subscription_id = models.CharField(max_length=36)
    azure_location = models.CharField(max_length=20)
Example #18
0
from django.db import models
from django.core.exceptions import ValidationError

from cinp.orm_django import DjangoCInP as CInP

from contractor.fields import name_regex
from contractor.Building.models import Foundation
from contractor.Survey.lib import foundationLookup

cinp = CInP('Survey', '0.1')


class SurveyException(ValueError):
    def __init__(self, code, message):
        super().__init__(message)
        self.message = message
        self.code = code

    @property
    def response_data(self):
        return {
            'class': 'SurveyException',
            'error': self.code,
            'message': self.message
        }

    def __str__(self):
        return 'SurveyException ({0}): {1}'.format(self.code, self.message)


@cinp.model()
Example #19
0
from django.db import models
from django.core.exceptions import ValidationError

from cinp.orm_django import DjangoCInP as CInP

from contractor.Site.models import Site
from contractor.Building.models import Foundation, Complex, FOUNDATION_SUBCLASS_LIST, COMPLEX_SUBCLASS_LIST

cinp = CInP( 'RaspberryPi', '0.1' )

FOUNDATION_SUBCLASS_LIST.append( 'raspberryPifoundation' )


@cinp.model( property_list=( 'state', 'type', 'class_list' ) )
class RaspberryPiFoundation( Foundation ):
  @property
  def subclass( self ):
    return self

  @property
  def type( self ):
    return 'RaspberryPi'

  @property
  def class_list( self ):
    return [ 'Metal', 'Manual', 'RaspberryPi' ]

  @cinp.list_filter( name='site', paramater_type_list=[ { 'type': 'Model', 'model': Site } ] )
  @staticmethod
  def filter_site( site ):
    return RaspberryPiFoundation.objects.filter( site=site )
Example #20
0
import uuid
from django.db import models

from cinp.orm_django import DjangoCInP as CInP

from User.models import User

cinp = CInP( 'Car', '0.1' )


@cinp.model()
class PartType( models.Model ):
  name = models.CharField( max_length=40, primary_key=True )
  description = models.CharField( max_length=255 )
  updated = models.DateTimeField( editable=False, auto_now=True )
  created = models.DateTimeField( editable=False, auto_now_add=True )

  @cinp.check_auth()
  @staticmethod
  def checkAuth( user, method, id_list, action=None ):
    return True

  def __str__( self ):
    return 'PartType "{0}"'.format( self.description )


@cinp.model()
class Part( models.Model ):
  id = models.CharField( max_length=36, primary_key=True, editable=False )
  part_type = models.ForeignKey( PartType, on_delete=models.CASCADE )
  price = models.FloatField()
Example #21
0
from django.db import models
from django.core.exceptions import ValidationError

from cinp.orm_django import DjangoCInP as CInP

from contractor.Site.models import Site
from contractor.Building.models import Foundation, Complex, FOUNDATION_SUBCLASS_LIST, COMPLEX_SUBCLASS_LIST
from contractor.Foreman.lib import RUNNER_MODULE_LIST
from contractor.BluePrint.models import FoundationBluePrint
from contractor.lib.config import getConfig, mergeValues

from contractor_plugins.Docker.module import start_stop, state, destroy, map_ports, unmap_ports

cinp = CInP( 'Docker', '0.1' )

FOUNDATION_SUBCLASS_LIST.append( 'dockerfoundation' )
COMPLEX_SUBCLASS_LIST.append( 'dockercomplex' )
RUNNER_MODULE_LIST.append( 'contractor_plugins.Docker.module' )


@cinp.model( property_list=( 'state', 'type' ) )
class DockerComplex( Complex ):
  @property
  def subclass( self ):
    return self

  @property
  def type( self ):
    return 'Docker'

  @property
Example #22
0
  add tracking logging, or some place to send tracking info
"""


class Request():
    def __init__(self, session, user=None):
        self.session = session
        if user is None:
            self.user = auth.get_user(self)
        else:
            self.user = user
        self.user._django_session = session
        self.META = {}


cinp = CInP('Auth', '2.0')


@cinp.staticModel(
    not_allowed_verb_list=['LIST', 'GET', 'DELETE', 'CREATE', 'UPDATE'])
class User():
    @cinp.action(return_type='String',
                 paramater_type_list=['String', 'String'])
    @staticmethod
    def login(username, password):
        user = auth.authenticate(username=username, password=password)
        if user is None:
            raise InvalidRequest('Invalid Login')

        request = Request(session=session_engine.SessionStore(None), user=user)
Example #23
0
from django.db import models
from django.dispatch import receiver
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import post_save, post_delete

from cinp.orm_django import DjangoCInP as CInP
from packrat.fields import name_regex, DISTRO_CHOICES, DISTRO_LENGTH, FILE_TYPE_LENGTH
"""
tags -
  list of required tags
  flag for auto happening
  optional change control requirements
"""

cinp = CInP('Attrib', '2.0')


class AttribException(ValueError):
    def __init__(self, code, message):
        super().__init__(message)
        self.message = message
        self.code = code

    @property
    def response_data(self):
        return {
            'exception': 'AttribException',
            'error': self.code,
            'message': self.message
        }
Example #24
0
File: models.py Project: pnhowe/MCP
from datetime import datetime, timezone

from django.db import models
from django.conf import settings
from django.core.exceptions import ValidationError

from cinp.orm_django import DjangoCInP as CInP
from cinp.client import NotFound

from mcp.fields import MapField, package_filename_regex, packagefile_regex, TAG_NAME_LENGTH, BLUEPRINT_NAME_LENGTH, BRANCH_NAME_LENGTH

from mcp.lib.t3kton import getContractor
from mcp.Project.models import Build, Project, Commit
from mcp.Resource.models import ResourceInstance, Network, Site

cinp = CInP('Processor', '0.1')

BUILDJOB_STATE_LIST = ('new', 'build', 'ran', 'reported', 'acknowledged',
                       'released')
INSTANCE_STATE_LIST = ('new', 'allocated', 'building', 'built', 'ran',
                       'releasing', 'released')


def base_config_values():
    return {
        '>package_list': ['nullunit'],
        'mcp_host': settings.MCP_HOST,
        'mcp_proxy': (settings.MCP_PROXY if settings.MCP_PROXY else '')
    }

Example #25
0
import json
from cinp.orm_django import DjangoCInP as CInP

from contractor.Records.lib import collection

cinp = CInP('Records', '0.1')


@cinp.staticModel(
    not_allowed_verb_list=['LIST', 'GET', 'DELETE', 'CREATE', 'UPDATE'])
class Recorder():
    @cinp.action(return_type={
        'type': 'String',
        'is_array': True
    },
                 paramater_type_list=[{
                     'type':
                     'String',
                     'choice_list':
                     ['Site', 'BluePrint', 'Structure', 'Foundation']
                 }, 'String', 'String', 'Integer'])
    @staticmethod
    def query(group, query, fields='{}', max_results=100):
        db = collection(group)
        try:
            query = json.loads(query)
        except Exception as e:
            raise ValueError('query is not valid JSON: "{0}"'.format(e))

        try:
            fields = json.loads(fields)
Example #26
0
from django.db import models
from django.core.exceptions import ValidationError

from cinp.orm_django import DjangoCInP as CInP

from contractor.Site.models import Site
from contractor.Building.models import Foundation, FOUNDATION_SUBCLASS_LIST
from contractor.Survey.models import Plot
# from contractor.Utilities.models import RealNetworkInterface, Networked
from contractor.Foreman.lib import RUNNER_MODULE_LIST

from contractor_plugins.IPMI.module import link_test, set_power, power_state, wait_for_poweroff

cinp = CInP('IPMI', '0.1')

FOUNDATION_SUBCLASS_LIST.append('ipmifoundation')
RUNNER_MODULE_LIST.append('contractor_plugins.IPMI.module')


@cinp.model(property_list=('state', 'type', 'class_list'))
class IPMIFoundation(Foundation):  # , Networked ):
    ipmi_username = models.CharField(max_length=16)
    ipmi_password = models.CharField(max_length=16)
    # ipmi_interface = models.ForeignKey( RealNetworkInterface )
    ipmi_ip_address = models.CharField(max_length=30)
    ipmi_sol_port = models.CharField(
        max_length=7,
        choices=(('console', 'console'), ('ttyS0', 'ttyS0'),
                 ('ttyS1', 'ttyS1'), ('ttyS2', 'ttyS2'), ('ttyS3', 'ttyS3')),
        default='ttyS1')
    plot = models.ForeignKey(Plot)
Example #27
0
File: models.py Project: pnhowe/MCP
from datetime import datetime

from django.db import models
from django.core.exceptions import ValidationError, ObjectDoesNotExist
from django.conf import settings

from cinp.orm_django import DjangoCInP as CInP

from mcp.fields import MapField, name_regex, package_filename_regex, packagefile_regex, TAG_NAME_LENGTH, PACKAGE_FILENAME_LENGTH, BLUEPRINT_NAME_LENGTH, BRANCH_NAME_LENGTH, BUILD_NAME_LENGTH
from mcp.lib.InternalGit import InternalGit
from mcp.lib.Git import Git
from mcp.lib.GitHub import GitHub
from mcp.lib.GitLab import GitLab
from mcp.Resource.models import Resource

cinp = CInP('Project', '0.1')

COMMIT_STATE_LIST = ('new', 'tested', 'built', 'doced', 'done')


def _markdownBlockQuote(lines):
    return '>' + re.sub(r'([\\`\*_{}\+\-\.\!#\(\)\[\]])', r'\\\1',
                        '\n>'.join(lines))


def _diffMarkDown(a, b):
    result = ''
    sm = difflib.SequenceMatcher(None, a, b)
    for group in sm.get_grouped_opcodes(3):
        for tag, i1, i2, j1, j2 in group:
            if tag == 'replace':
Example #28
0
  except ( Session.DoesNotExist, User.DoesNotExist ):
    return None

  if not session.user.isActive:
    return None

  if not session.isActive:
    return None

  return session.user


# TODO: this has many security issues, spend some time and think this out better
# TODO: should probably rename it auth as well, will also eventually need SSO abilities

cinp = CInP( 'User', '0.1' )


@cinp.model( property_list=[ 'isActive' ], not_allowed_verb_list=[ 'LIST', 'DELETE', 'CREATE' ], hide_field_list=[ 'password' ] )
class User( models.Model ):
  username = models.CharField( max_length=40, primary_key=True )
  password = models.CharField( editable=False, max_length=64 )
  nick_name = models.CharField( max_length=100, null=True, blank=True )
  superuser = models.BooleanField( default=False, editable=False )
  updated = models.DateTimeField( editable=False, auto_now=True )
  created = models.DateTimeField( editable=False, auto_now_add=True )

  @property
  def isActive( self ):
    return True
Example #29
0
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.db import models
from django.conf import settings
from django.apps import apps

from cinp.orm_django import DjangoCInP as CInP

from mcp.lib.t3kton import getContractor
from mcp.fields import name_regex

# NOTE: these are not "thread safe", there is not per-instance resource reservation
# make sure only one thing is calling these methods at a time...
# other than ready, that is thread safe

cinp = CInP('Resource', '0.1')


@cinp.model(not_allowed_verb_list=['CREATE', 'DELETE', 'UPDATE', 'CALL'])
class Site(models.Model):
    """
Site
  """
    name = models.CharField(max_length=40, primary_key=True)
    created = models.DateTimeField(editable=False, auto_now_add=True)
    updated = models.DateTimeField(editable=False, auto_now=True)

    def clean(self, *args, **kwargs):
        super().clean(*args, **kwargs)
        errors = {}

        if not name_regex.match(self.name):
Example #30
0
import random
from django.db import models
from django.core.exceptions import ValidationError

from cinp.orm_django import DjangoCInP as CInP

from contractor.Site.models import Site
from contractor.Building.models import Foundation, Complex, FOUNDATION_SUBCLASS_LIST, COMPLEX_SUBCLASS_LIST
from contractor.Foreman.lib import RUNNER_MODULE_LIST
from contractor.BluePrint.models import FoundationBluePrint
from contractor.lib.config import getConfig, mergeValues

from contractor_plugins.Proxmox.module import set_power, power_state, wait_for_poweroff, destroy, get_interface_map, set_interface_macs

cinp = CInP('Proxmox', '0.1')

FOUNDATION_SUBCLASS_LIST.append('proxmoxfoundation')
COMPLEX_SUBCLASS_LIST.append('proxmoxcomplex')
RUNNER_MODULE_LIST.append('contractor_plugins.Proxmox.module')


@cinp.model(property_list=('state', 'type'))
class ProxmoxComplex(
        Complex
):  # NOTE: will use the first member as the Host to send API requests to
    proxmox_username = models.CharField(max_length=50)
    proxmox_password = models.CharField(max_length=50)

    @property
    def subclass(self):
        return self