Beispiel #1
0
    def accept_devices(self, expected_devices):
        if len(
                self.get_devices_status(
                    "accepted", expected_devices=expected_devices)) == len(
                        get_mender_clients()):
            return

        # iterate over devices and accept them
        for d in self.get_devices(expected_devices=expected_devices):
            self.set_device_status(d["id"], "accepted")

        logger.info("Successfully bootstrap all clients")
Beispiel #2
0
    def make_artifact(self, image, device_type, artifact_name,
                      artifact_file_created):

        if artifact_name.startswith("artifact_name="):
            artifact_name = artifact_name.split('=')[1]

        cmd = "%s write rootfs-image -u %s -t %s -n %s -o %s" % (
            self.artifacts_tool_path, image, device_type, artifact_name,
            artifact_file_created.name)
        logger.info("Running: " + cmd)
        subprocess.check_call(cmd, shell=True)

        return artifact_file_created.name
Beispiel #3
0
    def upload_image(self, filename, description="abc"):
        image_path_url = self.get_deployments_base_path() + "artifacts"

        r = requests.post(image_path_url,
                          verify=False,
                          headers=self.auth.get_auth_token(),
                          files=(("description", (None, description)),
                                 ("artifact", (filename, open(filename),
                                               "multipart/form-data"))))

        logger.info("Received image upload status code: " +
                    str(r.status_code) + " with payload: " + str(r.text))
        assert r.status_code == requests.status_codes.codes.created
        return r.headers["location"]
Beispiel #4
0
    def check_expected_status(self, expected_status, deployment_id, max_wait=600, polling_frequency=2):
        timeout = time.time() + max_wait

        while time.time() <= timeout:
            data = self.get_status(status=expected_status)

            for deployment in data:
                if deployment["id"] == deployment_id:
                    logger.info("got expected deployment status (%s) for: %s" % (expected_status, deployment_id))
                    return
            else:
                time.sleep(polling_frequency)
                continue

        if time.time() > timeout:
            pytest.fail("Never found status: %s for %s" % (expected_status, deployment_id))
Beispiel #5
0
    def trigger_deployment(self, name, artifact_name, devices):
        deployments_path_url = self.get_deployments_base_path() + "deployments"

        trigger_data = {"name": name,
                        "artifact_name": artifact_name,
                        "devices": devices}

        headers = {'Content-Type': 'application/json'}
        headers.update(self.auth.get_auth_token())

        r = requests.post(deployments_path_url, headers=headers,
                          data=json.dumps(trigger_data), verify=False)

        logger.debug("triggering deployment with: " + json.dumps(trigger_data))
        assert r.status_code == requests.status_codes.codes.created

        deployment_id = str(r.headers['Location'].split("/")[-1])
        logger.info("Deployment id is: " + deployment_id)

        return deployment_id
Beispiel #6
0
    def get_devices_status(self, status=None, expected_devices=1):
        device_status_path = self.get_admission_base_path() + "devices"
        devices = None
        tries = 25

        for c, i in enumerate(range(tries)):
            time.sleep(c*3+5)
            try:
                logger.info("getting all devices from :%s" % (device_status_path))
                devices = requests.get(device_status_path, headers=self.auth.get_auth_token(), verify=False)
                assert devices.status_code == requests.status_codes.codes.ok
                assert len(devices.json()) == expected_devices
                break
            except AssertionError:
                if devices is not None and getattr(devices, "text"):
                    logger.info("fail to get devices (payload: %s), will try #%d times" % (devices.text, tries-c-1))
                else:
                    logger.info("failed to get devices, will try #%d times" % (tries-c-1))
                continue
        else:
            assert False, "Not able to get devices"

        devices_json = devices.json()

        if not status:
            return devices_json

        matching = []
        for d in devices_json:
            if d["status"] == status:
                matching.append(d)
        return matching
Beispiel #7
0
    def make_artifact(self, image, device_type, artifact_name,
                      artifact_file_created):

        if artifact_name.startswith("artifact_name="):
            artifact_name = artifact_name.split('=')[1]

        cmd = "%s write rootfs-image -u %s -t %s -n %s -o %s" % (
            self.artifacts_tool_path, image, device_type, artifact_name,
            artifact_file_created)
        logger.info("Running: " + cmd)

        try:
            subprocess.check_output(cmd, shell=True).strip()

        except subprocess.CalledProcessError:
            pytest.fail("Trying to create artifact failed.")
            return False

        except Exception, e:
            pytest.fail(
                "Unexpted error trying to create artifact: %s, error: %s" %
                (artifact_name, str(e)))
            return False
class Deployments(object):
    # track the last statistic for a deployment id
    last_statistic = {}
    auth = None

    def __init__(self, auth, adm):
        self.auth = auth
        self.adm = adm

    def get_deployments_base_path(self):
        return "https://%s/api/management/%s/deployments/" % (
            get_mender_gateway(), api_version)

    def upload_image(self, filename, description="abc"):
        image_path_url = self.get_deployments_base_path() + "artifacts"

        r = requests.post(image_path_url,
                          verify=False,
                          headers=self.auth.get_auth_token(),
                          files=(("description", (None, description)),
                                 ("size", (None,
                                           str(os.path.getsize(filename)))),
                                 ("artifact", (filename, open(filename),
                                               "application/octet-stream"))))

        logger.info("Received image upload status code: " +
                    str(r.status_code) + " with payload: " + str(r.text))
        assert r.status_code == requests.status_codes.codes.created
        return r.headers["location"]

    def trigger_deployment(self, name, artifact_name, devices):
        deployments_path_url = self.get_deployments_base_path() + "deployments"

        trigger_data = {
            "name": name,
            "artifact_name": artifact_name,
            "devices": devices
        }

        headers = {'Content-Type': 'application/json'}
        headers.update(self.auth.get_auth_token())

        r = requests.post(deployments_path_url,
                          headers=headers,
                          data=json.dumps(trigger_data),
                          verify=False)

        logger.debug("triggering deployment with: " + json.dumps(trigger_data))
        assert r.status_code == requests.status_codes.codes.created

        deployment_id = str(r.headers['Location'].split("/")[-1])
        logger.info("deployment [%s] triggered for device [%s]" %
                    (devices, deployment_id))

        return deployment_id

    def get_logs(self, device, deployment_id, expected_status=200):
        deployments_logs_url = self.get_deployments_base_path(
        ) + "deployments/%s/devices/%s/log" % (deployment_id, device)
        r = requests.get(deployments_logs_url,
                         headers=self.auth.get_auth_token(),
                         verify=False)
        assert r.status_code == expected_status

        logger.info("Logs contain " + str(r.text))
        return r.text

    def get_status(self, status=None):
        deployments_status_url = self.get_deployments_base_path(
        ) + "deployments"

        if status:
            deployments_status_url += "?status=%s" % (status)

        r = requests.get(deployments_status_url,
                         headers=self.auth.get_auth_token(),
                         verify=False)

        assert r.status_code == requests.status_codes.codes.ok
        return json.loads(r.text)

    def get_statistics(self, deployment_id):
        deployments_statistics_url = self.get_deployments_base_path(
        ) + "deployments/%s/statistics" % (deployment_id)
        r = requests.get(deployments_statistics_url,
                         headers=self.auth.get_auth_token(),
                         verify=False)
        assert r.status_code == requests.status_codes.codes.ok

        try:
            json.loads(r.text)
        except Exception, e:
            assert e is None

        if not self.last_statistic.setdefault(deployment_id, []) or \
            self.last_statistic[deployment_id][-1] != str(r.text):
            self.last_statistic[deployment_id].append(str(r.text))
            logger.info("Statistics contains new entry: " + str(r.text))

        return json.loads(r.text)