def test_service_load(self):
        Node = self.load_template('node')
        srv = tcol.instantiate_service(Node, 'testnode')

        # unload service from memory
        scol.drop_all()

        loaded = scol.load(Node, _serialize_service(srv))
        self.assertEqual(srv.name, loaded.name,
                         "name of the loaded service should be %s" % srv.name)
        self.assertEqual(
            srv.template_name, loaded.template_name,
            "template_name of the loaded service should be %s" %
            srv.template_name)
        self.assertEqual(srv.guid, loaded.guid,
                         "guid of the loaded service should be %s" % srv.guid)
        self.assertEqual(
            srv.version, loaded.version,
            "version of the loaded service should be %s" % srv.version)
        self.assertIsNotNone(srv.data,
                             "loaded service data should not be None")
        self.assertIsNotNone(srv.state,
                             "loaded service state should not be None")
        self.assertIsNotNone(srv.task_list,
                             "loaded service task_list should not be None")
Пример #2
0
def _create_node_service():
    service_found = scol.find(template_host='github.com',
                              template_account='zero-os',
                              template_name='node')
    if not service_found:
        template_found = tcol.find(host='github.com',
                                   account='zero-os',
                                   name='node')
        if not template_found:
            tcol.add_repo("https://github.com/zero-os/0-templates")

        template_found = tcol.find(host='github.com',
                                   account='zero-os',
                                   name='node')
        if not template_found:
            raise RuntimeError(
                "cannot create node service and --mode node is set")

        logger.info("create node service because --mode node is net")
        node = tcol.instantiate_service(template_found[0], 'local', {})
    else:
        node = service_found[0]

    try:
        node.state.check('actions', 'install', 'ok')
    except:
        node.schedule_action('install')
    node.schedule_action('_register')
    def test_instantiate_service_validation_fail(self):
        assert len(scol.find()) == 0

        Validate = self.load_template('validate')
        with pytest.raises(ValidationError) as err:
            srv = tcol.instantiate_service(Validate)

        assert len(scol.find()) == 0
 def test_service_load_wrong_template(self):
     Node = self.load_template('node')
     Vm = self.load_template('vm')
     srv = tcol.instantiate_service(Node, 'testnode')
     serialized = _serialize_service(srv)
     with self.assertRaises(BadTemplateError):
         # Try to load with the wrong template class
         scol.load(Vm, serialized)
Пример #5
0
 def test_service_load_wrong_name(self):
     Node = self.load_template('node')
     srv = tcol.instantiate_service(Node, 'testnode')
     path = srv.save()
     # rename the folder where the service have been saved
     new_path = os.path.join(os.path.dirname(path), 'other')
     os.rename(path, new_path)
     with self.assertRaises(BadTemplateError):
         scol.load(Node, new_path)
Пример #6
0
def createServiceHandler():
    '''
    create a new service
    It is handler for POST /services
    '''
    inputs = request.get_json()
    try:
        ServiceCreate_schema_validator.validate(inputs)
    except jsonschema.ValidationError as e:
        print(e)
        return jsonify(code=400, message="bad request body"), 400

    try:
        TemplateClass = tcol.get(inputs['template'])
    except TemplateNotFoundError:
        return jsonify(code=404,
                       message="template '%s' not found" %
                       inputs['template']), 404
    except TemplateConflictError:
        return jsonify(
            code=4090,
            message=
            "template with name '%s' is confusing, can't select template based only on its name, please use full UID"
            % inputs['template']), 409
    except ValueError as err:
        return jsonify(code=400, message=err.args[0]), 400

    try:
        service = tcol.instantiate_service(TemplateClass, inputs.get('name'),
                                           inputs.get('data', {}))
    except scol.ServiceConflictError:
        service = None
        return jsonify(code=409,
                       message="a service with name '%s' already exists" %
                       inputs['name']), 409
    except Exception as err:
        service = None
        return jsonify(code=500, message=str(err)), 500

    output = service_view(service)
    try:
        output['secret'] = auth.user_jwt.create({'service_guid': service.guid})
    except auth.user_jwt.SigningKeyNotFoundError as err:
        return jsonify(
            code=500,
            message='error creating user secret: no signing key available'
        ), 500
    except Exception as err:
        return jsonify(code=500,
                       message='error creating user secret: %s' %
                       str(err)), 500

    if inputs.get('public') is True:
        scol.set_service_public(service.guid)

    return jsonify(output), 201
    def test_service_add_task(self):
        Node = self.load_template('node')
        srv = tcol.instantiate_service(Node, 'testnode')
        task = srv.schedule_action('start')
        self.assertEqual(task.action_name, 'start',
                         "action name should be start")
        self.assertIsNotNone(task.guid, "task guid should not be None")

        task = srv.schedule_action('foo', args={'bar': 'foo'})
        self.assertDictEqual(task._args, {'bar': 'foo'})
        task.wait()
        assert task.duration != None and task.duration > 0

        self.assertEqual(
            task.result, 'result',
            "result of the task should be available in the task object")

        with self.assertRaises(ActionNotFoundError):
            srv.schedule_action('nonexist')

        with self.assertRaises(
                ActionNotFoundError,
                msg=
                'should raise when trying to schedule a attribute that is not callable'
        ):
            srv.schedule_action('guid')

        with self.assertRaises(
                BadActionArgumentError,
                msg=
                'should raise BadActionArgumentError when mandatory parameters is missing'
        ):
            task = srv.schedule_action('foo', args={'bor': 'foo'})

        with self.assertRaises(
                BadActionArgumentError,
                msg=
                "should raise if passing argument that are not part of the signature of the action"
        ) as err:
            srv.schedule_action('foo', args={'bar': 'foo', 'wrong_arg': 'bar'})
        assert err.exception.args[
            0] == 'arguments "wrong_arg" are not present in the signature of the action'

        t = srv.schedule_action('fookwargs',
                                args={
                                    'bar': 'foo',
                                    'other': 'xxx'
                                })
        t.wait()
        assert t.result == {
            'other': 'xxx'
        }, "action should be able to use **kwargs"
def _instantiate_service(service_descr):
    try:
        srv = tcol.instantiate_service(service_descr["template"],
                                       service_descr["service"],
                                       service_descr.get("data", None))
        return srv
    except ServiceConflictError as err:
        if err.service is None:
            raise j.exceptions.RuntimeError(
                "should have the conflicting service in the exception")
        # err.service is the conflicting service, that's the one we want to update
        # with the new data from the blueprint
        data = service_descr.get("data", {}) or {}
        err.service.data.update_secure(data)
 def test_instantiate_service(self):
     Node = self.load_template('node')
     srv = tcol.instantiate_service(Node, 'testnode')
     self.assertIsNotNone(srv, "service should not be None")
     self.assertEqual(srv.name, 'testnode',
                      "service name should be 'testnode'")
     self.assertIsNotNone(srv.guid, "service guid should not be None")
     self.assertEqual(srv.version, Node.version,
                      "service and template version should match")
     self.assertIsNotNone(srv.data, "service data should not be None")
     self.assertIsNotNone(srv.state, "service state should not be None")
     self.assertIsNotNone(srv.task_list,
                          "service task_list should not be None")
     self.assertIsNotNone(srv.gl_mgr,
                          "service greenlet manager should not be None")
Пример #10
0
    def test_cleanup_actions(self):
        Tmpl = self.load_template('cleanup')
        srv = tcol.instantiate_service(Tmpl)
        check_file = srv.data['output']

        try:
            srv.delete()
            with open(check_file) as f:
                check_file_content = f.read()
            ss = check_file_content.splitlines()
            assert len(ss) == 2
            assert ss[0] == 'cleanup1'
            assert ss[1] == 'cleanup2'
        finally:
            j.sal.fs.remove(check_file)
Пример #11
0
    def test_update_secure_overwrite(self):
        Node = self.load_template('node_updatedata')
        srv = tcol.instantiate_service(Node, 'testnode')
        self.assertEqual(srv.data['ip'], '')

        with self.assertRaises(
                ValueError,
                message=
                'should raise value error when trying to update data with a non dict object'
        ):
            srv.data.update_secure(data='string')

        task = srv.data.update_secure(data={'ip': '127.0.0.1'})
        task.wait()
        self.assertEqual(task.action_name, 'update_data')
        self.assertEqual(
            srv.data['ip'], '127.0.0.1',
            'if the template overwrite update_data, the data should be updated'
        )
Пример #12
0
    def create(self, template_uid, service_name=None, data=None, public=False):
        """
        Instantiate a service from a template on the local 0-robot

        :param template_uid: UID of the template to use a base class for the service
        :type template_uid: str
        :param service_name: name of the service, needs to be unique within the robot instance. If not specified a name is genrated, defaults to None
        :type service_name: str, optional
        :param data: data of the service to create, defaults to None
        :type data: dict
        :param public: is set to true, the service will be public, so anyone can schedule action on it, defaults to False
        :type public: bool, optional
        :return: the service created
        :rtype: Service object of the type of the template
        """
        # we can create a service locally, the local robot has the template
        template = tcol.get(template_uid)
        service = tcol.instantiate_service(template, service_name, data)
        if public:
            scol.set_service_public(service)
        return service
Пример #13
0
    def test_service_save_delete(self):
        Node = self.load_template('node')
        srv = tcol.instantiate_service(Node, 'testnode')

        srv.save()
        srv_dir = os.path.join(config.data_repo.path, srv.template_uid.host,
                               srv.template_uid.account, srv.template_uid.repo,
                               srv.template_uid.name, srv.name, srv.guid)

        self.assertTrue(os.path.exists(srv_dir),
                        "directory of the saved service should exists")
        for x in ['service.yaml', 'data.yaml', 'state.yaml']:
            self.assertTrue(os.path.exists(os.path.join(srv_dir, x)),
                            "%s file service should exists" % x)

        service_info = j.data.serializer.yaml.load(
            os.path.join(srv_dir, 'service.yaml'))
        for k in ['template', 'guid', 'name', 'version']:
            self.assertTrue(k in service_info,
                            "%s should be present in service.yaml" % k)

        srv.delete()
        self.assertFalse(
            os.path.exists(os.path.dirname(srv_dir)),
            "directory of the saved service not should exists anymore")

        log_file_pattern = os.path.join(j.dirs.LOGDIR, 'zrobot',
                                        srv.guid) + '*'
        log_files = glob.glob(log_file_pattern)
        self.assertEqual(
            len(log_files), 0,
            "log files of the services should not should exists anymore")

        with self.assertRaises(
                scol.ServiceNotFoundError,
                message='service should not be found in memory anymore'):
            scol.get_by_guid(srv.guid)
Пример #14
0
 def test_data_protected(self):
     Tmpl = self.load_template('cleanup')
     srv = tcol.instantiate_service(Tmpl)
     # should raise if we try to overwrite the data property
     with pytest.raises(RuntimeError):
         srv.data = {}
Пример #15
0
 def test_service_load_dir_not_exists(self):
     Node = self.load_template('node')
     srv = tcol.instantiate_service(Node, 'testnode')
     path = srv.save()
     with self.assertRaises(FileNotFoundError):
         scol.load(Node, '/tmp/zerorobot-test-not-exists')