Пример #1
0
def delete_job(_id):
    record = Job.find_by_id(ObjectId(_id))
    if not record:
        return jsonify({'message': 'record not found', 'code': 104040}), 404

    update = {'$set': {'status': -1}}

    Job.update_one({'_id': record['_id']}, update=update)
    extra = {'record': record}
    logger.info('delete job', extra=extra)

    return jsonify({
        'message': 'ok',
        'code': 0,
    })
Пример #2
0
 def test_get_job(self, check_book, parse_file_inventory,
                  parse_cmdb_inventory):
     data = self.get_data('playbook_job')
     data['name'] = str(uuid.uuid4())
     data['status'] = 1
     url = self.get_api_path('/jobs/%s' % str(ObjectId()))
     response = self.client.get(url, headers=self.jwt_headers)
     self.assert400(response)
     self.assertResponseCode(response, 154001)
     result = self.add_test_data(Job, data)
     url = self.get_api_path('/jobs/%s' % str(result.inserted_id))
     parse_cmdb_inventory.return_value = ''
     parse_file_inventory.return_value = ''
     response = self.client.get(url, headers=self.jwt_headers)
     self.assert200(response)
     Job.update_one({'_id': result.inserted_id}, {
         '$set': {
             'maintainer': [self.user.get('username')],
             'book_id': str(ObjectId())
         }
     })
     response = self.client.get(url, headers=self.jwt_headers)
     parse_file_inventory.assert_called()
     check_book.assert_called()
     self.assert200(response)
     self.assertResponseDataHasKey(response, 'logs')
     self.assertResponseDataHasKey(response, 'previewContent')
     self.assertResponseDataHasKey(response, 'record')
     self.assertResponseDataHasKey(response, 'roles')
     data = self.get_data('adhoc_job')
     data['maintainer'] = [self.user.get('username')]
     data['template'] = {
         'inventory_type': 'adhoc',
         'inventory': 'localhost'
     }
     result = self.add_test_data(Job, data)
     url = self.get_api_path('/jobs/%s' % str(result.inserted_id))
     response = self.client.get(url, headers=self.jwt_headers)
     parse_cmdb_inventory.assert_called()
     self.assertResponseDataHasKey(response, 'logs')
     self.assertResponseDataHasKey(response, 'previewContent')
     self.assertResponseDataHasKey(response, 'record')
Пример #3
0
def add_jobs():
    """
    add job
    TODO(sang)
    :return: json
    """
    body = request.get_json()
    user = login_user
    if not body:
        return jsonify({
            'message': 'miss required params',
            'code': 104000,
        }), 400

    job_type = body.get('type')
    if job_type == 'adhoc':
        return add_adhoc()

    current_id = body.get('currentId')
    record = None
    if current_id:
        record = Job.find_by_id(current_id)
        if not record:
            return jsonify({'message': 'job not found', 'code': 104044}), 400

    payload = load_ansible_playbook(body)
    if payload.get('message') is not 'ok':
        return jsonify(payload), 400

    data = payload.get('data')
    options = data.get('options')
    is_check = body.get('check')
    private_key = data.get('private_key')
    wk = Workspace()
    res = wk.load_book_from_db(name=data.get('book_name'),
                               roles=data.get('roles'))
    if not res:
        return jsonify({
            'message': 'book not found',
            'code': 104000,
        }), 400

    entry = wk.get_book_entry(data.get('book_name'), data.get('entry'))
    dry_run = bool(is_check)
    options['check'] = dry_run
    if dry_run:
        with NamedTemporaryFile('w+t', delete=True) as fd:
            if private_key:
                key_text = get_credential_content_by_id(
                    private_key, 'private_key')
                if not key_text:
                    return jsonify({
                        'message': 'invalid private_key',
                        'code': 104033,
                    }), 401

                fd.write(key_text)
                fd.seek(0)
                options['private_key'] = fd.name

            play = PlayBookRunner(data['inventory'],
                                  options,
                                  callback=CallbackModule())
            play.run(entry)

            return jsonify({
                'message': 'ok',
                'code': 0,
                'data': {
                    'result': play.get_result(),
                    'options': options
                }
            })

    name = data.get('name')
    existed = Job.find_one({'name': name})
    if existed and not current_id:
        return jsonify({
            'message': 'name existed',
            'code': 104001,
        }), 400

    token = str(base64.b64encode(bytes(current_request_id(), 'utf8')), 'utf8')
    new_record = {
        'name': name,
        'type': 'playbook',
        'token': token,
        'description': data.get('description'),
        'book_id': data.get('book_id'),
        'template': data.get('template'),
        'extra': data.get('extra'),
        'entry': data['entry'],
        'status': data['status'],
        'maintainer': [user.get('username')],
        'created_at': int(time.time()),
        'updated_at': datetime.datetime.now().isoformat(),
    }

    if record:
        Job.update_one({'_id': record['_id']}, update={'$set': new_record})
    else:
        Job.insert_one(new_record)

    return jsonify({
        'message': 'ok',
        'code': 0,
    })
Пример #4
0
def add_adhoc():
    payload = request.get_json()
    if not payload:
        return jsonify({
            'message': 'invalid params',
            'code': 104001,
        }), 400

    module = payload.get('module')
    args = payload.get('args')
    inventory = payload.get('inventory')
    private_key = payload.get('private_key')
    verbosity = payload.get('verbosity', 0)
    name = payload.get('name')
    schedule = payload.get('schedule')
    check = payload.get('check')
    job_id = payload.get('job_id')
    extra_options = payload.get('extraOptions')
    status = int(payload.get('status', 0))
    notification = payload.get('notification')
    maintainer = payload.get('maintainer') or []
    if maintainer and isinstance(maintainer, list):
        users = User.find({'username': {'$in': maintainer}})
        names = list(map(lambda i: i['username'], users))
        maintainer.extend(names)

    if login_user.get('username'):
        maintainer.append(login_user.get('username'))

    if not job_id:
        existed = Job.find_one({'name': name})
        if existed and existed.get('status') != -1:
            return jsonify({'message': 'name exist', 'code': 104007}), 400

    if not module or not inventory or not name:
        return jsonify({
            'message': 'miss required params',
            'code': 104002,
        }), 400

    # check_module = db.collection('ansible_modules').find_one({
    #     'name': module
    # })
    #
    # if not check_module:
    #     return jsonify({
    #         'message': 'invalid module',
    #         'code': 104003,
    #     }), 400

    inventory_content = parse_cmdb_inventory(inventory)
    if not inventory_content:
        return jsonify({
            'message': 'invalid inventory',
            'code': 104004,
        }), 400

    options = {}
    if extra_options:
        options.update(extra_options)

    if verbosity:
        options['verbosity'] = verbosity

    if check:
        with NamedTemporaryFile('w+t', delete=True) as fd:
            if private_key:
                key_text = get_credential_content_by_id(
                    private_key, 'private_key')
                if not key_text:
                    return jsonify({
                        'message': 'invalid private key',
                        'code': 104004,
                    }), 400

                fd.write(key_text)
                fd.seek(0)
                options['private_key'] = fd.name

            tasks = [{'action': {'module': module, 'args': args}}]
            hosts = inventory_content
            runner = AdHocRunner(hosts, options=options)
            runner.run('all', tasks)
            result = runner.get_result()

            return jsonify({'message': 'ok', 'code': 0, 'data': result})

    else:
        token = str(base64.b64encode(bytes(current_request_id(), 'utf8')),
                    'utf8')
        data = {
            'name': name,
            'template': {
                'inventory': inventory,
                'private_key': private_key,
                'verbosity': verbosity,
                'module': module,
                'args': args,
                'extraOptions': extra_options,
            },
            'extra': {
                'schedule': schedule,
                'notification': notification,
            },
            'token': token,
            'maintainer': maintainer,
            'type': 'adhoc',
            'created_at': time.time(),
            'status': status,
            'add_by': login_user.get('username')
        }

        if job_id:
            record = Job.find_one({'_id': ObjectId(job_id)})
            if not record:
                return jsonify({
                    'message': 'record not found',
                    'code': 104040
                }), 404

            update = {
                '$set': data,
            }
            Job.update_one({'_id': ObjectId(job_id)}, update=update)
        else:
            Job.insert_one(data)

    return jsonify({
        'message': 'ok',
        'code': 0,
    })