예제 #1
0
def device_show(opts):
    url = inventory_url(opts.service, '/devices/{}'.format(opts.device))
    with api_from_opts(opts) as api:
        rsp = do_simple_get(api, url)
        logging.debug("%r", rsp.status_code)

        dump_device_attributes(rsp.json())
예제 #2
0
def devices_list(opts):
    def devlist_printer(rsp):
        devslist = rsp.json()
        logging.info("Devices:")
        if opts.format == 'plain':
            for dev in devslist:
                attrs = repack_attrs(dev.get('attributes'))
                result = ""
                if opts.attributes:
                    attributes = opts.attributes.split(",")
                    for attribute in attributes:
                        attribute = attribute.strip()
                        if attribute == 'id':
                            result = result + "{}={} ".format(attribute, dev['id'])
                        elif attribute == 'updated':
                            result = result + "{}={} ".format(attribute, dev['updated_ts'])
                        else:
                            result = result + "{}={} ".format(attribute, attrs.get(attribute, '<undefined>'))
                print(result)

        elif opts.format == 'json':
            jsonprinter(rsp)

    # TODO add pagination (go through all pages)
    url = inventory_url(opts.service, '/devices?per_page={}'.format(opts.limit))
    with api_from_opts(opts) as api:
        do_simple_get(api, url, printer=devlist_printer)
예제 #3
0
def list_users(opts):
    logging.info('list users')
    with api_from_opts(opts) as api:
        do_simple_get(
            api,
            user_url(opts.service, '/users'),
            printer=lambda rsp: [dump_user(user) for user in rsp.json()])
예제 #4
0
def list_device_auths(opts):
    with api_from_opts(opts) as api:
        do_simple_get(
            api,
            admissions_url(opts.service),
            printer=lambda rsp:
            [dump_device_auth(dev, showkey=False) for dev in rsp.json()])
예제 #5
0
def do_authorize(opts):
    url = device_url(opts.service, '/authentication/auth_requests')

    try:
        key = load_privkey(opts.device_key)
    except IOError:
        logging.error('failed to load key from %s', opts.device_key)
        return

    identity = json.dumps({
        'mac': opts.mac_address,
    })
    logging.debug('identity: %s', identity)
    data = json.dumps({
        'id_data': identity,
        'pubkey': str(key.publickey().exportKey(), 'utf-8'),
        'tenant_token': opts.tenant_token,
    })
    logging.debug('request data: %s', data)
    signature = sign(data, key)
    hdrs = {'X-MEN-Signature': signature, 'Content-Type': 'application/json'}
    with api_from_opts(opts) as api:
        rsp = api.post(url, data=data, headers=hdrs)

        if rsp.status_code == 200:
            logging.info('request successful')
            logging.info('token: %s', rsp.text)
            save_file(opts.device_token, rsp.text)
            return True
        else:
            logging.warning('request failed: %s %s', rsp, rsp.text)
    return False
예제 #6
0
def do_deployments_logs(opts):
    logging.debug('get log for deployment %s on device %s', opts.id,
                  opts.devid)
    url = deployments_url(opts.service,
                          '{}/devices/{}/log'.format(opts.id, opts.devid))
    with api_from_opts(opts) as api:
        do_simple_get(api, url, printer=simpleprinter)
예제 #7
0
def device_api_from_opts(opts):
    api = api_from_opts(opts)

    if os.path.exists(opts.device_token):
        token = load_file(opts.device_token)
        api.auth = JWTAuth(token)

    return api
예제 #8
0
def device_show(opts):
    url = inventory_url(opts.service, '/devices/{}'.format(opts.device))

    with api_from_opts(opts) as api:
        rsp = do_simple_get(api, url)
        logging.debug("%r", rsp.status_code)

        dump_device_attributes(rsp.json())
예제 #9
0
def device_api_from_opts(opts):
    api = api_from_opts(opts)

    if os.path.exists(opts.device_token):
        token = load_file(opts.device_token)
        api.auth = JWTAuth(token)

    return api
예제 #10
0
def set_device_auth_status(opts, status):
    url = admissions_url(opts.service, '/{}/status'.format(opts.device))
    logging.debug('device auth URL: %s', url)
    with api_from_opts(opts) as api:
        do_request(api, url, method='PUT',
                   json={
                       'status': status
                   })
예제 #11
0
def device_group(opts):
    url = inventory_url(opts.service, '/devices/{}/group'.format(opts.device))
    if not opts.group_set and not opts.group_delete:
        with api_from_opts(opts) as api:
            do_simple_get(api, url)
    elif opts.group_set:
        group = {
            'group': opts.group_set,
        }
        method = 'PUT'
    elif opts.group_delete:
        url = inventory_url(opts.service, '/devices/{}/group/{}'.format(opts.device,
                                                                        opts.group_delete))
        group = {
            'group': opts.group_delete,
        }
        method = 'DELETE'

    with api_from_opts(opts) as api:
        do_request(api, url, method=method, success=204,
                   json=group)
예제 #12
0
def devices_list(opts):
    def devlist_printer(rsp):
        devslist = rsp.json()
        print('devices:')
        for dev in devslist:
            attrs = repack_attrs(dev.get('attributes'))
            print('  {} (type: {}, updated: {})'.format(
                dev['id'], attrs.get('device_type', '<undefined>'),
                dev['updated_ts']))

    url = inventory_url(opts.service, '/devices')
    with api_from_opts(opts) as api:
        do_simple_get(api, url, printer=devlist_printer)
예제 #13
0
def do_user_login_initial(opts):
    logging.debug('initial user login')

    url = user_url(opts.service, '/auth/login')
    with api_from_opts(opts) as api:
        # use basic auth with user provided password and login
        api.auth = None
        rsp = api.post(url)

        if rsp.status_code == 200:
            logging.info('initial login successful')
            logging.info('token: %s', rsp.text)
            save_file(opts.user_token, rsp.text)
        else:
            logging.warning('request failed: %s %s', rsp, rsp.text)
예제 #14
0
def do_user_login_initial(opts):
    logging.debug('initial user login')

    url = user_url(opts.service, '/auth/login')
    with api_from_opts(opts) as api:
        # use basic auth with user provided password and login
        api.auth = None
        rsp = api.post(url)

        if rsp.status_code == 200:
            logging.info('initial login successful')
            logging.info('token: %s', rsp.text)
            save_file(opts.user_token, rsp.text)
        else:
            logging.warning('request failed: %s %s', rsp, rsp.text)
예제 #15
0
def do_user_create_initial(opts):
    logging.debug('create initial user')

    url = user_url(opts.service, '/users/initial')
    with api_from_opts(opts) as api:
        # use basic auth with user provided password and login
        rsp = api.post(url,
                       json={
                           'email': opts.user,
                           'password': opts.password,
                       })
        if rsp.status_code == 201:
            logging.info('initial user created')
            logging.info(rsp.text)
        else:
            logging.warning('request failed: %s %s', rsp, rsp.text)
예제 #16
0
def do_user_create_initial(opts):
    logging.debug('create initial user')

    url = user_url(opts.service, '/users/initial')
    with api_from_opts(opts) as api:
        # use basic auth with user provided password and login
        rsp = api.post(url,
                       json={
                           'email': opts.user,
                           'password': opts.password,
                       })
        if rsp.status_code == 201:
            logging.info('initial user created')
            logging.info(rsp.text)
        else:
            logging.warning('request failed: %s %s', rsp, rsp.text)
예제 #17
0
def do_deployments_add(opts):
    logging.debug('lookup deployment %s', opts.name)
    url = deployments_url(opts.service)
    with api_from_opts(opts) as api:
        rsp = api.post(url,
                       json={
                           'name': opts.name,
                           'artifact_name': opts.artifact_name,
                           'devices': opts.device,
                       })
        if rsp.status_code == 201:
            # created
            location = rsp.headers.get('Location', '')
            print("created with URL: {}".format(location))
            print('deployment ID: ', location.rsplit('/')[-1])
        else:
            logging.warning('request failed: %s %s', rsp, rsp.json())
예제 #18
0
def do_deployments_add(opts):
    logging.debug('lookup deployment %s', opts.name)
    url = deployments_url(opts.service)
    with api_from_opts(opts) as api:
        rsp = api.post(url,
                       json={
                           'name': opts.name,
                           'artifact_name': opts.artifact_name,
                           'devices': opts.device,
                       })
        if rsp.status_code == 201:
            # created
            location = rsp.headers.get('Location', '')
            print("created with URL: {}".format(location))
            print('deployment ID: ', location.rsplit('/')[-1])
        else:
            logging.warning('request failed: %s %s', rsp, rsp.json())
예제 #19
0
def do_artifacts_artifact_add(opts):
    logging.debug('add artifact %r', opts)
    url = artifacts_url(opts.service)
    image = {
        'name': opts.name,
        'description': opts.description,
    }
    # build contents of multipart/form-data, image meta must come first, hence
    # we use an OrderedDict to preserve the order
    files = OrderedDict()
    for k, v in image.items():
        files[k] = (None, io.StringIO(v))
    # followed by firmware data
    # but first, try to find out the size of firmware data
    files['size'] = str(os.stat(opts.infile).st_size)
    files['artifact'] = (opts.infile, open(opts.infile, 'rb'),
                         "application/octet-stream", {})

    encoder = MultipartEncoder(files)

    if sys.stderr.isatty():
        try:
            from requests_toolbelt import MultipartEncoderMonitor
            from clint.textui.progress import Bar as ProgressBar

            pb = ProgressBar(expected_size=encoder.len,
                             filled_char='=',
                             every=1024 * 1024)
            monitor = MultipartEncoderMonitor(
                encoder, lambda mon: pb.show(mon.bytes_read))
            encoder = monitor
        except ImportError:
            pass

    with api_from_opts(opts) as api:
        rsp = api.post(url,
                       data=encoder,
                       headers={'Content-Type': encoder.content_type})
        if rsp.status_code == 201:
            # created
            location = rsp.headers.get('Location', '')
            print("created with URL: {}".format(location))
            print('artifact ID: ', location.rsplit('/')[-1])
        else:
            errorprinter(rsp)
예제 #20
0
def do_authorize(opts):
    url = device_url(opts.service, '/authentication/auth_requests')

    try:
        key = load_privkey(opts.device_key)
    except IOError:
        logging.error('failed to load key from %s', opts.device_key)
        return

    identity = json.dumps({
        'mac': opts.mac_address,
    })
    logging.debug('identity: %s', identity)
    data = json.dumps({
        'id_data': identity,
        'pubkey': str(key.publickey().exportKey(), 'utf-8'),
        'tenant_token': opts.tenant_token,
    })
    logging.debug('request data: %s', data)
    signature = sign(data, key)
    hdrs = {
        'X-MEN-Signature': signature,
        'Content-Type': 'application/json'
    }
    with api_from_opts(opts) as api:
        rsp = api.post(url,
                       data=data,
                       headers=hdrs)

        if rsp.status_code == 200:
            logging.info('request successful')
            logging.info('token: %s', rsp.text)
            save_file(opts.device_token, rsp.text)
            return True
        else:
            logging.warning('request failed: %s %s', rsp, rsp.text)
    return False
예제 #21
0
def show_device_auth(opts):
    url = admissions_url(opts.service, '/{}'.format(opts.device))
    with api_from_opts(opts) as api:
        rsp = do_simple_get(api, url,
                            printer=lambda rsp: dump_device_auth(rsp.json()))
예제 #22
0
def list_devices(opts):
    with api_from_opts(opts) as api:
        do_simple_get(api, authentication_url(opts.service, '/devices'),
                      printer=lambda rsp: [dump_device_brief(dev)
                                           for dev in rsp.json()])
예제 #23
0
def do_deployments_find(opts):
    logging.debug('lookup deployment %s', opts.name)
    url = deployments_url(opts.service)
    with api_from_opts(opts) as api:
        do_simple_get(api, url, params={'name': opts.name})
예제 #24
0
def delete_device(opts):
    url = authentication_url(opts.service, '/devices/{}'.format(opts.device))
    with api_from_opts(opts) as api:
        rsp = do_simple_delete(api, url)
예제 #25
0
def do_deployments_devices(opts):
    logging.debug('get deployment %s devices', opts.id)
    url = deployments_url(opts.service, '{}/devices'.format(opts.id))
    with api_from_opts(opts) as api:
        do_simple_get(api, url)
예제 #26
0
def group_show(opts):
    url = inventory_url(opts.service, 'groups/{}/devices'.format(opts.group))
    with api_from_opts(opts) as api:
        do_simple_get(api, url)
예제 #27
0
def do_artifacts_download(opts):
    logging.debug('get artifact %s download', opts.id)
    url = artifacts_url(opts.service, '/{}/download'.format(opts.id))

    with api_from_opts(opts) as api:
        do_simple_get(api, url)
예제 #28
0
def show_device(opts):
    url = authentication_url(opts.service, '/devices/{}'.format(opts.device))
    with api_from_opts(opts) as api:
        rsp = do_simple_get(api, url,
                            printer=lambda rsp: dump_device(rsp.json()))
예제 #29
0
def list_devices(opts):
    with api_from_opts(opts) as api:
        do_simple_get(
            api,
            authentication_url(opts.service, '/devices'),
            printer=lambda rsp: [dump_device_brief(dev) for dev in rsp.json()])
예제 #30
0
def delete_device(opts):
    url = authentication_url(opts.service, '/devices/{}'.format(opts.device))
    with api_from_opts(opts) as api:
        rsp = do_simple_delete(api, url)
예제 #31
0
def show_device(opts):
    url = authentication_url(opts.service, '/devices/{}'.format(opts.device))
    with api_from_opts(opts) as api:
        rsp = do_simple_get(api,
                            url,
                            printer=lambda rsp: dump_device(rsp.json()))
예제 #32
0
def count_devices(opts):
    url = authentication_url(opts.service,
                             '/devices/count?{}'.format(opts.status))
    with api_from_opts(opts) as api:
        rsp = do_simple_get(api, url)
예제 #33
0
def count_devices(opts):
    url = authentication_url(opts.service, '/devices/count?{}'.format(opts.status))
    with api_from_opts(opts) as api:
        rsp = do_simple_get(api, url)
예제 #34
0
def set_device_auth_status(opts, status):
    url = admissions_url(opts.service, '/{}/status'.format(opts.device))
    logging.debug('device auth URL: %s', url)
    with api_from_opts(opts) as api:
        do_request(api, url, method='PUT', json={'status': status})
예제 #35
0
def do_artifacts_show(opts):
    logging.debug('get artifact %s download', opts.id)
    url = artifacts_url(opts.service, opts.id)
    with api_from_opts(opts) as api:
        do_simple_get(api, url)
예제 #36
0
def show_device_auth(opts):
    url = admissions_url(opts.service, '/{}'.format(opts.device))
    with api_from_opts(opts) as api:
        rsp = do_simple_get(api,
                            url,
                            printer=lambda rsp: dump_device_auth(rsp.json()))
예제 #37
0
def do_artifacts_list(opts):
    logging.debug('list artifacts')
    url = artifacts_url(opts.service)
    with api_from_opts(opts) as api:
        do_simple_get(api, url)
예제 #38
0
def do_deployments_find(opts):
    logging.debug('lookup deployment %s', opts.name)
    url = deployments_url(opts.service)
    with api_from_opts(opts) as api:
        do_simple_get(api, url, params={'name': opts.name})
예제 #39
0
def list_users(opts):
    logging.info('list users')
    with api_from_opts(opts) as api:
        do_simple_get(api, user_url(opts.service, '/users'),
                      printer=lambda rsp: [dump_user(user)
                                           for user in rsp.json()])
예제 #40
0
def group_list(opts):
    url = inventory_url(opts.service, 'groups')
    with api_from_opts(opts) as api:
        do_simple_get(api, url)
예제 #41
0
def do_deployments_devices(opts):
    logging.debug('get deployment %s devices', opts.id)
    url = deployments_url(opts.service,
                          '{}/devices'.format(opts.id))
    with api_from_opts(opts) as api:
        do_simple_get(api, url)
예제 #42
0
def do_deployments_status(opts):
    logging.debug('get deployment %s', opts.id)
    url = deployments_url(opts.service, opts.id)
    with api_from_opts(opts) as api:
        do_simple_get(api, url)
예제 #43
0
def do_deployments_logs(opts):
    logging.debug('get log for deployment %s on device %s', opts.id, opts.devid)
    url = deployments_url(opts.service,
                          '{}/devices/{}/log'.format(opts.id, opts.devid))
    with api_from_opts(opts) as api:
        do_simple_get(api, url, printer=simpleprinter)
예제 #44
0
def list_device_auths(opts):
    with api_from_opts(opts) as api:
        do_simple_get(api, admissions_url(opts.service),
                      printer=lambda rsp: [dump_device_auth(dev,
                                                            showkey=False)
                                           for dev in rsp.json()])
예제 #45
0
def do_deployments_status(opts):
    logging.debug('get deployment %s', opts.id)
    url = deployments_url(opts.service, opts.id)
    with api_from_opts(opts) as api:
        do_simple_get(api, url)