Perform firmware flashing on a redfish system

        :param file_url: url to firmware bits.
        :param redfish_inst: redfish instance
        :raises: IloError, on an error from iLO.
164843
def flash_firmware(self, redfish_inst,  file_url):
        
        action_data = {
            'ImageURI': file_url,
        }
        target_uri = self._get_firmware_update_element().target_uri
        try:
            self._conn.post(target_uri, data=action_data)
        except sushy.exceptions.SushyError as e:
            msg = (('The Redfish controller failed to update firmware '
                    'with file %(file)s Error %(error)s') %
                   {'file': file_url, 'error': str(e)})
            LOG.debug(msg)  # noqa
            raise exception.IloError(msg)

        self.wait_for_redfish_firmware_update_to_complete(redfish_inst)
        try:
            state, percent = self.get_firmware_update_progress()
        except sushy.exceptions.SushyError as e:
            msg = ('Failed to get firmware progress update '
                   'Error %(error)s' % {'error': str(e)})
            LOG.debug(msg)
            raise exception.IloError(msg)

        if state == "Error":
            msg = 'Unable to update firmware'
            LOG.debug(msg)  # noqa
            raise exception.IloError(msg)
        elif state == "Unknown":
            msg = 'Status of firmware update not known'
            LOG.debug(msg)  # noqa
        else:  # "Complete" | "Idle"
            LOG.info('Flashing firmware file: %s ... done', file_url)
895643
def open(self, file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None):
        
        urn = Urn(file)
        urn_path = urn.path()

        remote_file_exists = self.check(urn_path)

        if not remote_file_exists:
            if 'r' in mode:
                raise RemoteResourceNotFound(urn_path)
        elif self.is_dir(urn_path):
            raise OptionNotValid(name='file', value=file)

        with tempfile.TemporaryDirectory() as temp_dir:
            local_path = f'{temp_dir}{os.path.sep}{file}'

            if remote_file_exists:
                self.download_file(file, local_path)
            else:
                if ('w' in mode or 'a' in mode or 'x' in mode) and os.path.sep in local_path:
                    os.makedirs(local_path.rsplit(os.path.sep, 1)[0], exist_ok=True)

            with open(file=local_path, mode=mode, buffering=buffering, encoding=encoding, errors=errors,
                      newline=newline, closefd=closefd, opener=opener) as f:
                yield f

            if 'w' in mode or 'a' in mode or 'x' in mode:
                self.upload_file(file, local_path)
171197
def on_IOError(self, e):
        

        sys.stderr.write("Error: %s: \"%s\"\n" % (e.strerror, e.filename))
140252
def on_same_fs(request):
    
    filename = request.POST['filename']
    checksum_in = request.POST['checksum']

    checksum = 0
    try:
        data = open(filename, 'rb').read(32)
        checksum = zlib.adler32(data, checksum) & 0xffffffff
        if checksum == int(checksum_in):
            return HttpResponse(content=json.dumps({'success': True}),
                                content_type=JSON, status=200)
    except (IOError, ValueError):
        pass

    return HttpResponse(content=json.dumps({'success': False}),
                        content_type=JSON, status=200)
1228638
def flash_danger(resource, action = nil, e: nil, name: nil)
      raise 'expected an ActiveRecord resource' unless resource.respond_to?(:errors) && (name || resource.class.respond_to?(:model_name))

      action ||= resource.respond_to?(:new_record?) ? (resource.new_record? ? :create : :update) : :save
      action = action.to_s.gsub('_', ' ')

      messages = flash_errors(resource, e: e)

      name ||= resource.to_s.presence

      ["Unable to #{action}", (" #{name}" if name), (": #{messages}" if messages)].compact.join.html_safe
    end
80054
def _firmware_update(firmwarefile='', host='',
                     directory=''):
    '''
    
    '''
    dest = os.path.join(directory, firmwarefile[7:])

    __salt__['cp.get_file'](firmwarefile, dest)

    username = __pillar__['proxy']['admin_user']
    password = __pillar__['proxy']['admin_password']
    __salt__['dracr.update_firmware'](dest,
                                      host=host,
                                      admin_username=username,
                                      admin_password=password)
616152
def check_url_filetoupload(self):
        # type: () -> None
        
        if self.file_to_upload is None:
            if 'url' in self.data:
                if 'resource_type' not in self.data:
                    self.data['resource_type'] = 'api'
                if 'url_type' not in self.data:
                    self.data['url_type'] = 'api'
            else:
                raise HDXError('Either a url or a file to upload must be supplied!')
        else:
            if 'url' in self.data:
                if self.data['url'] != hdx.data.dataset.Dataset.temporary_url:
                    raise HDXError('Either a url or a file to upload must be supplied not both!')
            if 'resource_type' not in self.data:
                self.data['resource_type'] = 'file.upload'
            if 'url_type' not in self.data:
                self.data['url_type'] = 'upload'
            if 'tracking_summary' in self.data:
                del self.data['tracking_summary']
1328105
def load(self, url, offset=0, length=-1):
        

        # if starting with . or /, can only be a file path..
        file_only = url.startswith(('/', '.'))

        # convert to filename
        filename = from_file_url(url)
        if filename != url:
            file_only = True
            url = filename

        try:
            # first, try as file
            afile = open(url, 'rb')

        except IOError:
            if file_only:
                raise

            return super(LocalFileLoader, self).load(url, offset, length)

        if offset > 0:
            afile.seek(offset)

        if length >= 0:
            return LimitReader(afile, length)
        else:
            return afile
645188
def open(self, file, mode='r', buffering=-1, encoding=None,
             errors=None, newline=None, closefd=True, opener=None):
        
        if opener is not None and sys.version_info < (3, 3):
            raise TypeError(
                "open() got an unexpected keyword argument 'opener'")
        fake_open = FakeFileOpen(self.filesystem, use_io=True)
        return fake_open(file, mode, buffering, encoding, errors,
                         newline, closefd, opener)
299886
public URLConnection connectWithRedirect(URL theURL) throws IOException {
        URLConnection conn = null;

        String accept_header = buildAcceptHeader();
        int redirect_count = 0;
        boolean done = false;

        while (!done) {
            if (theURL.getProtocol().equals("file")) {
                return null;
            }
            Boolean isHttp = (theURL.getProtocol().equals("http") || theURL
                    .getProtocol().equals("https"));

            logger.debug("Requesting: " + theURL.toString());

            conn = theURL.openConnection();

            if (isHttp) {
                logger.debug("Accept: " + accept_header);
                conn.setRequestProperty("Accept", accept_header);
            }

            conn.setConnectTimeout(60000);
            conn.setReadTimeout(60000);

            conn.connect();

            done = true; // by default quit after one request

            if (isHttp) {
                logger.debug("Response: " + conn.getHeaderField(0));
                int rc = ((HttpURLConnection) conn).getResponseCode();

                if ((rc == HttpURLConnection.HTTP_MOVED_PERM)
                        || (rc == HttpURLConnection.HTTP_MOVED_TEMP)
                        || (rc == HttpURLConnection.HTTP_SEE_OTHER)
                        || (rc == 307)) {
                    if (redirect_count > 10) {
                        return null; // Error: too many redirects
                    }
                    redirect_count++;
                    String loc = conn.getHeaderField("Location");
                    if (loc != null) {
                        theURL = new URL(loc);
                        done = false;
                    } else {
                        return null; // Bad redirect
                    }
                } else if ((rc < 200) || (rc >= 300)) {
                    return null; // Unsuccessful
                }
            }
        }
        return conn;
    }
1072059
def open(self, url, mode='r', stdio=True):
        
        # doesn't need to use config, because the object is already created
        res = urlsplit(url)

        if not res.scheme:
            if not res.path or res.path == '-':
                if not stdio:
                    raise IOError("unable to open '%s'" % (url,))

                if 'w' in mode:
                    return sys.stdout
                return sys.stdin

            return open(res.path, mode)

        if res.scheme in ('https', 'http', 'ftp'):
            req = requests.get(res.geturl(), stream=True)
            # TODO error check
            return req.raw
            #return urllib2.urlopen(res.geturl())

        raise IOError("unable to open '%s'" % (url,))
937416
def set_fw_upgrade(uri, tpm_override_flag = true)
      new_action = { 'Action' => 'InstallFromURI', 'FirmwareURI' => uri, 'TPMOverrideFlag' => tpm_override_flag }
      response = rest_post('/redfish/v1/Managers/1/UpdateService/', body: new_action)
      response_handler(response)
      true
    end
209418
def uploadFile(self, filename, ispickle=False, athome=False):
        
        print("Uploading file {} to Redunda.".format(filename))

        _, tail = os.path.split(filename)
        
        url = "https://redunda.sobotics.org/bots/data/{}?key={}".format(tail, self.key)
        
        #Set the content type to 'application/octet-stream'
        header = {"Content-type": "application/octet-stream"}
        
        filedata = ""

        if athome:
            filename = str(os.path.expanduser("~")) + filename

        #Read the data from a file to a string.
        if filename.endswith(".pickle") or ispickle:
            try:
                with open(filename, "rb") as fileToRead:
                    data = pickle.load(fileToRead)
            except pickle.PickleError as perr:
                print("Pickling error occurred: {}".format(perr))
                return
            filedata = json.dumps(data)
        else:
            try:
                with open(filename, "r") as fileToRead:
                    filedata = fileToRead.read()
            except IOError as ioerr:
                print("IOError occurred: {}".format(ioerr))
                return

        requestToMake = request.Request(url, data=filedata.encode("utf-8"), headers=header)

        #Make the request.
        response = request.urlopen(requestToMake)

        if response.code >= 400:
            print("Error occurred while uploading file '{}' with error code {}.".format(filename,response.code))
1031137
def file_to_url(self, file_rel_path):
        """"""
        _abs_path = os.path.abspath(file_rel_path)
        return urlparse.urlparse(_abs_path, scheme='file').geturl()
737640
def _get_loader_for_url(self, url):
        
        parts = url.split('://', 1)
        if len(parts) < 2:
            type_ = 'file'
        else:
            type_ = parts[0]

        if '+' in type_:
            profile_name, scheme = type_.split('+', 1)
            if len(parts) == 2:
                url = scheme + '://' + parts[1]
        else:
            profile_name = ''
            scheme = type_

        loader = self.cached.get(type_)
        if loader:
            return loader, url

        loader_cls = self._get_loader_class_for_type(scheme)

        if not loader_cls:
            raise IOError('No Loader for type: ' + scheme)

        profile = self.kwargs

        if self.profile_loader:
            profile = self.profile_loader(profile_name, scheme)

        loader = loader_cls(**profile)

        self.cached[type_] = loader
        return loader, url
1276673
def check_firmware_update_component(func):
    """"""
    @six.wraps(func)
    def wrapper(self, filename, component_type):
        """Wrapper around ``update_firmware`` call.

        :param filename: location of the raw firmware file.
        :param component_type: Type of component to be applied to.
        """
        component_type = component_type and component_type.lower()
        if (component_type not in SUPPORTED_FIRMWARE_UPDATE_COMPONENTS):
            msg = ("Got invalid component type for firmware update: "
                   "``update_firmware`` is not supported on %(component)s" %
                   {'component': component_type})
            LOG.error(self._(msg))  # noqa
            raise exception.InvalidInputError(msg)

        return func(self, filename, component_type)

    return wrapper
899501
def s3_request(func: Callable):
    

    @wraps(func)
    def wrapper(url: str, *args, **kwargs):
        try:
            return func(url, *args, **kwargs)
        except ClientError as exc:
            if int(exc.response["Error"]["Code"]) == 404:
                raise FileNotFoundError("file {} not found".format(url))
            else:
                raise

    return wrapper