Example #1
0
    def deployments(self, name=None, **kwargs):
        skip = ['id', 'owner_id']

        def _encode(s):
            try:
                return json.loads(s)
            except ValueError:
                return {}
        if name:
            depl = Deployment.my(request).filter(
                Deployment.name == name).first()
            if depl:
                return O.deployment(**depl.serialize(
                    skip=skip,
                    rel=[('content', 'content',
                          lambda p: _encode(p))]))
            else:
                return O.error(msg="Cannot find deployment '%s'" % name)
        else:
            depl = sorted([d.serialize(skip=skip)
                           for d in Deployment.my(request).all()],
                          key=lambda d: d['name'])
            return O._anon(deployments=depl,
                           quota=dict(allowed=request.user.tier.deployments))
        return O.none()
Example #2
0
 def profile(self, *args, **kwargs):
     user = User.visible(request).filter(
         User.username == request.user.username).one()
     used = {
         'total_repos': 0,
         'cron_jobs': 0,
         'api_keys': 0,
         'users': 0,
         'groups': 0,
         'nodes': 0
     }
     used['total_repos'] = Repository.count(request)
     used['cron_jobs'] = Job.count(request)
     used['api_keys'] = ApiKey.count(request)
     used['users'] = User.count(request)
     used['groups'] = Group.count(request)
     used['nodes'] = Node.count(request)
     used['deployments'] = Deployment.count(request)
     used['cloud_profiles'] = CloudProfile.count(request)
     quotas = dict((k, dict(allowed=v, used=used[k]))
                   for k, v in request.user.tier._items.items()
                   if k in used)
     return O.user(quotas=quotas,
                   plan=request.user.tier.name,
                   **user.serialize(skip=['id', 'org_id', 'password'],
                                    rel=[('groups.name', 'groups')]))
Example #3
0
 def delete(self, *args, **kwargs):
     name = "/".join(args)
     depl = Deployment.my(request).filter(Deployment.name == name).first()
     if not depl:
         return O.error(msg="Cannot find deployment '%s'" % name)
     _cleanup(depl)
     request.db.delete(depl)
Example #4
0
    def stop(self, name, *args, **kwargs):
        name = name or kwargs['name']

        depl = Deployment.my(request).filter(Deployment.name == name).first()
        if not depl:
            return O.error(msg="Cannot find deployment '%s'" % name)
        depl.status = "Stopped"
        _cleanup(depl)
Example #5
0
class Deployments(HookController):

    __hooks__ = [DbHook(), ErrorHook()]

    @expose('json', generic=True)
    @wrap_command(Deployment)
    def deployments(self, name=None, **kwargs):
        skip = ['id', 'owner_id']

        def _encode(s):
            try:
                return json.loads(s)
            except ValueError:
                return {}
        if name:
            depl = Deployment.my(request).filter(
                Deployment.name == name).first()
            if depl:
                return O.deployment(**depl.serialize(
                    skip=skip,
                    rel=[('content', 'content',
                          lambda p: _encode(p))]))
            else:
                return O.error(msg="Cannot find deployment '%s'" % name)
        else:
            depl = sorted([d.serialize(skip=skip)
                           for d in Deployment.my(request).all()],
                          key=lambda d: d['name'])
            return O._anon(deployments=depl,
                           quota=dict(allowed=request.user.tier.deployments))
        return O.none()

    @deployments.when(method='POST', template='json')
    @deployments.wrap_create(integrity_error=lambda er:
                             "Duplicate deployment name")
    def create(self, name, **kwargs):
        if request.method != "POST":
            return O.none()
        name = name or kwargs['name']

        try:
            user = User.visible(request).filter(
                User.id == request.user.id).first()
            content = kwargs.pop('content')
            if not isinstance(content, dict):
                content = json.loads(content)

            _validate(content)

        except KeyError, kerr:
            return O.error(msg="Missing content data: %s" % kerr)
        depl = Deployment(name=name, content=json.dumps(content),
                          status='Pending',
                          owner=user)
        request.db.add(depl)
Example #6
0
    def restart(self, name, *args, **kwargs):
        name = name or kwargs['name']

        depl = Deployment.my(request).filter(Deployment.name == name).first()
        if not depl:
            return O.error(msg="Cannot find deployment '%s'" % name)

        content = json.loads(depl.content)
        _validate(content)
        request.db.commit()
        depl.status = "Starting"
        task_ids = _execute(depl, **kwargs)

        return O.success(status="ok", task_ids=task_ids)
Example #7
0
    def start(self, name, *args, **kwargs):
        name = name or kwargs['name']

        depl = Deployment.my(request).filter(Deployment.name == name).first()
        if not depl:
            return O.error(msg="Cannot find deployment '%s'" % name)
        if depl.status not in ['Pending', 'Stopped']:
            return O.error(msg="Deployment must be Pending or Stopped "
                           "to be Started.")

        content = json.loads(depl.content)
        _validate(content)
        request.db.commit()
        depl.status = "Starting"
        task_ids = _execute(depl, **kwargs)

        return O.success(status="ok", task_ids=task_ids)
Example #8
0
    def create(self, name=None, **kwargs):
        if not kwargs:
            kwargs = request.json
        name = name or kwargs['name']
        automation = kwargs['automation']
        params = kwargs.get('params')
        if params:
            if not isinstance(params, dict):
                params = json.loads(params)
        else:
            params = {}
        private = (bool(kwargs.get('private'))
                   and not kwargs.get('private') in ['0', 'false', 'False'])

        if not EXE_PATH:
            return O.error(msg="Scheduler job executable not found on server")

        per = kwargs['period']
        period = Period(per)
        if not period.is_valid():
            return O.error(msg="Period %s is not valid" % period)

        depl = Deployment.my(request).filter(
            Deployment.name == automation).first()
        if not depl:
            return O.error(msg="Invalid Automation name")

        user = request.db.query(User).filter(User.id == request.user.id).one()
        job = Job(name=name,
                  owner=user,
                  enabled=True,
                  params=json.dumps(params),
                  deployment=depl,
                  private=private,
                  exec_period=period._)

        request.db.add(job)
        request.db.commit()
        cron_name = job.uid
        # Post-create
        url = EXE_PATH % cron_name
        if job.params:
            url = "%s -e '%s'" % (url, job.params)
        success, res = schedule_manager.add(request.user.username, cron_name,
                                            period, url, job.name)
Example #9
0
    def script(self, *args, **kwargs):
        full_path = "/" + "/".join(args)
        LOG.info("Received execute script request [%s] from: %s" %
                 (full_path, request.client_addr))

        key = kwargs.pop('key', None)
        if not getattr(request, "user", None):
            if not key:
                return O.error(msg="Missing auth key")

            api_key = get_api_key(key)
            if not api_key:
                return abort(401)
            user_id = api_key.user_id
            request.user = cached_user(api_key.user)
        else:
            user_id = request.user.id
        user = request.db.query(User).filter(User.id == user_id).one()

        targets = kwargs.pop("targets")
        if not targets:
            return O.error(msg="Targets is a mandatory field")
        targets = [t.strip() for t in SPLITTER.split(targets) if t.strip()]

        env = kwargs.pop('env', {})

        env.update(flatten_params(request.params))
        dep_data = dict()
        dep_data['steps'] = []
        step = dict(target=targets, content=dict(path=full_path))
        dep_data['steps'].append(step)

        depl = Deployment(name="Execute: %s" % full_path,
                          content=json.dumps(dep_data),
                          status='Pending',
                          owner=user)

        task_ids = _execute(depl, env=env, dont_save=True, **kwargs)
        if task_ids:
            return O.success(status="ok", **task_ids)
        else:
            return O.error(msg="Cannot execute script")
Example #10
0
    def rebuild(self, name, **kwargs):
        name = name or kwargs['name']
        depl = Deployment.my(request).filter(Deployment.name == name).first()
        if not depl:
            return O.error(msg="Cannot find deployment '%s'" % name)
        content = kwargs.pop('content')
        if not isinstance(content, dict):
            content = json.loads(content)

        depl.status = 'Rebuilding'
        if "new_name" in kwargs:
            depl.name = kwargs["new_name"]
        request.db.commit()

        _validate(content)
        depl.content = json.dumps(content)

        task_ids = _execute(depl, **kwargs)

        return O.success(status="ok", task_ids=task_ids)
 def profile(self, *args, **kwargs):
     user = User.visible(request).filter(
         User.username == request.user.username).one()
     used = {'total_repos': 0, 'cron_jobs': 0,
             'api_keys': 0, 'users': 0, 'groups': 0, 'nodes': 0}
     used['total_repos'] = Repository.count(request)
     used['cron_jobs'] = Job.count(request)
     used['api_keys'] = ApiKey.count(request)
     used['users'] = User.count(request)
     used['groups'] = Group.count(request)
     used['nodes'] = Node.count(request)
     used['deployments'] = Deployment.count(request)
     used['cloud_profiles'] = CloudProfile.count(request)
     quotas = dict((k, dict(allowed=v, used=used[k]))
                   for k, v in request.user.tier._items.items()
                   if k in used)
     return O.user(quotas=quotas,
                   plan=request.user.tier.name,
                   **user.serialize(
                       skip=['id', 'org_id', 'password'],
                       rel=[('groups.name', 'groups')]))
Example #12
0
    def patch(self, **kw):
        kwargs = kw or request.json
        name = kwargs.pop('name')

        job = Job.own(request).filter(Job.name == name).first()
        if not job:
            return O.error(msg="Job %s not found" % name)

        name_to_update = False
        if kwargs.get('new_name'):
            new_name = kwargs['new_name']
            job.name = new_name
            name_to_update = True

        automation = kwargs.get('automation')
        if automation:
            depl = Deployment.my(request).filter(
                Deployment.name == automation).first()
            if not depl:
                return O.error(msg="Invalid Automation name")
            job.deployment = depl

        period = None
        per = kwargs.get('period')
        period_to_update = False
        if per:
            period = Period(per)
            if not period.is_valid():
                return O.error(msg="Period %s is not valid" % period)

            if period.is_only_minutes() and period.total_minutes < 5:
                return O.error(msg="Period cannot be less than 5 minutes")

        params = kwargs.get('params')
        if params:
            if isinstance(params, dict):
                params = json.dumps(params)
            job.params = params

        if period and period._ != job.exec_period:
            job.exec_period = period._
            period_to_update = True

        enabled = kwargs.get('enabled')
        enable_to_update = False
        if enabled is not None:
            enabled = enabled not in ['0', 'false', 'False']
            if enabled != job.enabled:
                enable_to_update = True
            job.enabled = enabled

        private = kwargs.get('private')
        if private is not None:
            job.private = private not in ['0', 'false', 'False']

        request.db.add(job)
        request.db.commit()

        if period_to_update or name_to_update:
            success, res = schedule_manager.edit(request.user.username,
                                                 job.uid, period, job.name)

        if enable_to_update:
            if job.enabled:
                url = EXE_PATH % job.uid
                schedule_manager.add(request.user.username, job.uid,
                                     job.exec_period, url, job.name)
            else:
                schedule_manager.delete(request.user.username, job.uid)