Try<Nothing> write_certificate_file(X509* x509, const Path& path) { // We use 'FILE*' here because it is an API requirement by openssl. FILE* file = fopen(path.value.c_str(), "wb"); if (file == nullptr) { return Error("Failed to open file '" + stringify(path) + "' for writing"); } if (PEM_write_X509(file, x509) != 1) { fclose(file); return Error("Failed to write certificate to file '" + stringify(path) + "': PEM_write_X509"); } fclose(file); return Nothing(); }
void FlagsBase::add( Option<T>* option, const std::string& name, const std::string& help, F validate) { // Don't bother adding anything if the pointer is NULL. if (option == NULL) { return; } Flag flag; flag.name = name; flag.help = help; flag.boolean = typeid(T) == typeid(bool); // NOTE: See comment above in T* overload of FlagsBase::add for why // we need to take the FlagsBase* parameter. flag.load = [option](FlagsBase*, const std::string& value) -> Try<Nothing> { // NOTE: 'fetch' "retrieves" the value if necessary and then // invokes 'parse'. See 'fetch' for more details. Try<T> t = fetch<T>(value); if (t.isSome()) { *option = Some(t.get()); } else { return Error("Failed to load value '" + value + "': " + t.error()); } return Nothing(); }; flag.stringify = [option](const FlagsBase&) -> Option<std::string> { if (option->isSome()) { return stringify(option->get()); } return None(); }; flag.validate = [option, validate](const FlagsBase&) -> Option<Error> { return validate(*option); }; add(flag); }
Try<Nothing> open(const std::string& path) { // Check if we've already opened a library. if (handle_ != NULL) { return Error("Library already opened"); } handle_ = dlopen(path.c_str(), RTLD_NOW); if (handle_ == NULL) { return Error( "Could not load library '" + path + "': " + dlerror()); } path_ = path; return Nothing(); }
Try<Nothing> checkpoint(const std::string& path, const T& t) { // Create the base directory. std::string base = Path(path).dirname(); Try<Nothing> mkdir = os::mkdir(base); if (mkdir.isError()) { return Error("Failed to create directory '" + base + "': " + mkdir.error()); } // NOTE: We create the temporary file at 'base/XXXXXX' to make sure // rename below does not cross devices (MESOS-2319). // // TODO(jieyu): It's possible that the temporary file becomes // dangling if slave crashes or restarts while checkpointing. // Consider adding a way to garbage collect them. Try<std::string> temp = os::mktemp(path::join(base, "XXXXXX")); if (temp.isError()) { return Error("Failed to create temporary file: " + temp.error()); } // Now checkpoint the instance of T to the temporary file. Try<Nothing> checkpoint = internal::checkpoint(temp.get(), t); if (checkpoint.isError()) { // Try removing the temporary file on error. os::rm(temp.get()); return Error("Failed to write temporary file '" + temp.get() + "': " + checkpoint.error()); } // Rename the temporary file to the path. Try<Nothing> rename = os::rename(temp.get(), path); if (rename.isError()) { // Try removing the temporary file on error. os::rm(temp.get()); return Error("Failed to rename '" + temp.get() + "' to '" + path + "': " + rename.error()); } return Nothing(); }
Try<Nothing> TearDownMixin() { // Return to previous working directory and cleanup the sandbox. Try<Nothing> chdir = os::chdir(cwd); if (chdir.isError()) { return Error("Failed to chdir into '" + cwd + "': " + chdir.error()); } if (sandbox.isSome()) { Try<Nothing> rmdir = os::rmdir(sandbox.get()); if (rmdir.isError()) { return Error("Failed to rmdir '" + sandbox.get() + "'" ": " + rmdir.error()); } } return Nothing(); }
void VectorImage::OnSVGDocumentLoaded() { MOZ_ASSERT(mSVGDocumentWrapper->GetRootSVGElem(), "Should have parsed successfully"); MOZ_ASSERT(!mIsFullyLoaded && !mHaveAnimations, "These flags shouldn't get set until OnSVGDocumentLoaded. " "Duplicate calls to OnSVGDocumentLoaded?"); CancelAllListeners(); // XXX Flushing is wasteful if embedding frame hasn't had initial reflow. mSVGDocumentWrapper->FlushLayout(); mIsFullyLoaded = true; mHaveAnimations = mSVGDocumentWrapper->IsAnimated(); // Start listening to our image for rendering updates. mRenderingObserver = new SVGRootRenderingObserver(mSVGDocumentWrapper, this); // Tell *our* observers that we're done loading. if (mProgressTracker) { Progress progress = FLAG_SIZE_AVAILABLE | FLAG_HAS_TRANSPARENCY | FLAG_FRAME_COMPLETE | FLAG_DECODE_COMPLETE | FLAG_ONLOAD_UNBLOCKED; if (mHaveAnimations) { progress |= FLAG_IS_ANIMATED; } // Merge in any saved progress from OnImageDataComplete. if (mLoadProgress) { progress |= *mLoadProgress; mLoadProgress = Nothing(); } mProgressTracker->SyncNotifyProgress(progress, GetMaxSizedIntRect()); } EvaluateAnimation(); }
Try<Nothing> write_key_file(EVP_PKEY* private_key, const Path& path) { // We use 'FILE*' here because it is an API requirement by openssl. FILE* file = fopen(path.value.c_str(), "wb"); if (file == nullptr) { return Error("Failed to open file '" + stringify(path) + "' for writing"); } if (PEM_write_PrivateKey( file, private_key, nullptr, nullptr, 0, nullptr, nullptr) != 1) { fclose(file); return Error("Failed to write private key to file '" + stringify(path) + "': PEM_write_PrivateKey"); } fclose(file); return Nothing(); }
Result<void> UdpLink::process() { Frame frame; struct sockaddr_in6 sin6 = {0}; struct iovec iov[2] = {{&frame, sizeof(Frame)}, {_buffer.data(), _buffer.size()}}; struct msghdr msg = { &sin6, sizeof(sin6), iov, 2 }; int r = recvmsg(_fd, &msg, MSG_DONTWAIT); if (r < 0) return Error(std::string("recvmsg failed: ") + strerror(errno)); Message message; message.setSeq(frame.seq); ByteArray data(_buffer.data(), r - iov[0].iov_len); message.setData(data); processMessage(message); return Nothing(); }
Try<Nothing> copyToLocal( std::string from, const std::string& to) { from = absolutePath(from); // Copy from HDFS. Try<std::string> command = strings::format( "%s fs -copyToLocal '%s' '%s'", hadoop, from, to); CHECK_SOME(command); Try<std::string> out = os::shell(command.get()); if (out.isError()) { return Error(out.error()); } return Nothing(); }
// Send a request to the subprocess and wait for its signal that the // work has been done. Try<Nothing> MemoryTestHelper::requestAndWait(const string& request) { if (s.isNone()) { return Error("The subprocess has not been spawned yet"); } Try<Nothing> write = os::write(s->in().get(), request + "\n"); if (write.isError()) { cleanup(); return Error("Fail to sync with the subprocess: " + write.error()); } Result<string> read = os::read(s->out().get(), sizeof(DONE)); if (!read.isSome() || read.get() != string(sizeof(DONE), DONE)) { cleanup(); return Error("Failed to sync with the subprocess"); } return Nothing(); }
Try<Nothing> checkpoint( const string& path, const google::protobuf::Message& message) { // Create the base directory. Try<Nothing> result = os::mkdir(os::dirname(path).get()); if (result.isError()) { return Error("Failed to create directory '" + os::dirname(path).get() + "': " + result.error()); } // Now checkpoint the protobuf to disk. result = ::protobuf::write(path, message); if (result.isError()) { return Error("Failed to checkpoint \n" + message.DebugString() + "\n to '" + path + "': " + result.error()); } return Nothing(); }
Try<Nothing> check() { // As advised in libnl, we use numeric values, instead of defined // macros (which creates compile time dependency), to check // capabilities. // Check NL_CAPABILITY_ROUTE_LINK_VETH_GET_PEER_OWN_REFERENCE. if (nl_has_capability(2) == 0) { return Error( "Capability ROUTE_LINK_VETH_GET_PEER_OWN_REFERENCE is not available"); } // Check NL_CAPABILITY_ROUTE_LINK_CLS_ADD_ACT_OWN_REFERENCE. if (nl_has_capability(3) == 0) { return Error( "Capability ROUTE_LINK_CLS_ADD_ACT_OWN_REFERENCE is not available"); } return Nothing(); }
Future<Nothing> untar( const Path& input, const Option<Path>& directory) { vector<string> argv = { "tar", "-x", // Extract/unarchive. "-f", // Input file to extract/unarchive. input }; // Add additional flags. if (directory.isSome()) { argv.emplace_back("-C"); argv.emplace_back(directory.get()); } return launch("tar", argv) .then([] () {return Nothing();}); }
void VectorImage::OnSVGDocumentError() { CancelAllListeners(); mError = true; if (mProgressTracker) { // Notify observers about the error and unblock page load. Progress progress = FLAG_ONLOAD_UNBLOCKED | FLAG_HAS_ERROR; // Merge in any saved progress from OnImageDataComplete. if (mLoadProgress) { progress |= *mLoadProgress; mLoadProgress = Nothing(); } mProgressTracker->SyncNotifyProgress(progress); } }
Try<Nothing> checkpoint(const std::string& path, const std::string& message) { std::cout << "Checkpointing '" << message << "' to '" << path << "'" << std::endl; // Create the base directory. Try<Nothing> result = os::mkdir(os::dirname(path).get()); if (result.isError()) { return Error("Failed to create directory '" + os::dirname(path).get() + "': " + result.error()); } // Now checkpoint the message to disk. result = os::write(path, message); if (result.isError()) { return Error("Failed to checkpoint '" + message + "' to '" + path + "': " + result.error()); } return Nothing(); }
Try<Nothing> initialize(const mesos::Parameters& parameters) { foreach (const mesos::Parameter& parameter, parameters.parameter()) { if (parameter.has_key() && parameter.has_value()) { flags[parameter.key()] = parameter.value(); } else { return Error("Invalid key-value parameters"); } } // We expect that when specifying the module, a module parameter // was also specified, i.e.: // "modules": [{"name": "org_apache_mesos_TestModule", // "flags": [{"key": "operation", "value": "sum"}]}] // The expected value for the key "operation" is "sum". if (flags.contains("operation") && flags["operation"] != "sum") { return Error("Invalid 'operation'"); } return Nothing(); }
// Write out the given protobuf to the specified file descriptor by // first writing out the length of the protobuf followed by the contents. // NOTE: On error, this may have written partial data to the file. inline Try<Nothing> write(int fd, const google::protobuf::Message& message) { if (!message.IsInitialized()) { return Error("Uninitialized protocol buffer"); } // First write the size of the protobuf. uint32_t size = message.ByteSize(); std::string bytes = std::string((char*) &size, sizeof(size)); Try<Nothing> result = os::write(fd, bytes); if (result.isError()) { return Error("Failed to write size: " + result.error()); } if (!message.SerializeToFileDescriptor(fd)) { return Error("Failed to write/serialize message"); } return Nothing(); }
// Write out the string to the file at the current fd position. inline Try<Nothing> write(int fd, const std::string& message) { size_t offset = 0; while (offset < message.length()) { ssize_t length = ::write(fd, message.data() + offset, message.length() - offset); if (length < 0) { // TODO(benh): Handle a non-blocking fd? (EAGAIN, EWOULDBLOCK) if (errno == EINTR) { continue; } return ErrnoError(); } offset += length; } return Nothing(); }
Future<Nothing> tar( const Path& input, const Path& output, const Option<Path>& directory, const Option<Compression>& compression) { vector<string> argv = { "tar", "-c", // Create archive. "-f", // Output file. output }; // Add additional flags. if (directory.isSome()) { argv.emplace_back("-C"); argv.emplace_back(directory.get()); } if (compression.isSome()) { switch (compression.get()) { case Compression::GZIP: argv.emplace_back("-z"); break; case Compression::BZIP2: argv.emplace_back("-j"); break; case Compression::XZ: argv.emplace_back("-J"); break; default: UNREACHABLE(); } } argv.emplace_back(input); return launch("tar", argv) .then([] () {return Nothing();}); }
Try<Nothing> copyToLocal( const std::string& from, const std::string& to) { // Copy from HDFS. Try<std::string> command = strings::format( "%s fs -copyToLocal '%s' '%s'", hadoop, from, to); CHECK_SOME(command); std::ostringstream output; Try<int> status = os::shell(&output, command.get() + " 2>&1"); if (status.isError()) { return Error(status.error()); } else if (status.get() != 0) { return Error(command.get() + "\n" + output.str()); } return Nothing(); }
Optional<QString> ImageHeaderData::validate() const { if (type == ImageResource::Type::Invalid) return ImageHeader::tr("Invalid type"); if (width <= 0) return ImageHeader::tr("Invalid width: %1").arg(width); if (height <= 0) return ImageHeader::tr("Invalid height: %1").arg(height); if ((type == ImageResource::Type::VolumeTexture) && depth <= 0) return ImageHeader::tr("Invalid depth: %1").arg(depth); if (imageFormat == QImage::Format::Format_Invalid) return ImageHeader::tr("Invalid image format"); if (imageCount <= 0) return ImageHeader::tr("Invalid image count: %1").arg(imageCount); if (frameDelay < 0) return ImageHeader::tr("Invalid image delay: %1").arg(frameDelay); if (loopCount < -1) return ImageHeader::tr("Invalid loop count: %1").arg(loopCount); return Nothing(); }
Try<Nothing> SetUpMixin() { // Save the current working directory. cwd = os::getcwd(); // Create a temporary directory for the test. Try<std::string> directory = os::mkdtemp(); if (directory.isError()) { return Error("Failed to mkdtemp: " + directory.error()); } // We get the `realpath` of the temporary directory because some // platforms, like macOS, symlink `/tmp` to `/private/var`, but // return the symlink name when creating temporary directories. // This is problematic because a lot of tests compare the // `realpath` of a temporary file. Result<std::string> realpath = os::realpath(directory.get()); if (realpath.isError()) { return Error("Failed to get realpath of '" + directory.get() + "'" ": " + realpath.error()); } else if (realpath.isNone()) { return Error("Failed to get realpath of '" + directory.get() + "'" ": No such directory"); } sandbox = realpath.get(); // Run the test out of the temporary directory we created. Try<Nothing> chdir = os::chdir(sandbox.get()); if (chdir.isError()) { return Error("Failed to chdir into '" + sandbox.get() + "'" ": " + chdir.error()); } return Nothing(); }
Try<Nothing> rm(std::string path) { // Make sure 'to' starts with a '/'. path = path::join("", path); Try<std::string> command = strings::format( "%s fs -rm '%s'", hadoop, path); CHECK_SOME(command); std::ostringstream output; Try<int> status = os::shell(&output, command.get() + " 2>&1"); if (status.isError()) { return Error(status.error()); } else if (status.get() != 0) { return Error(command.get() + "\n" + output.str()); } return Nothing(); }
// Indempotent error flagging routine. If a decoder is open, shuts it down. void RasterImage::DoError() { // If we've flagged an error before, we have nothing to do if (mError) { return; } // We can't safely handle errors off-main-thread, so dispatch a worker to // do it. if (!NS_IsMainThread()) { HandleErrorWorker::DispatchIfNeeded(this); return; } // Put the container in an error state. mError = true; // Stop animation and release our FrameAnimator. if (mAnimating) { StopAnimation(); } mAnimationState = Nothing(); mFrameAnimator = nullptr; // Release all locks. mLockCount = 0; SurfaceCache::UnlockImage(ImageKey(this)); // Release all frames from the surface cache. SurfaceCache::RemoveImage(ImageKey(this)); // Invalidate to get rid of any partially-drawn image content. NotifyProgress(NoProgress, IntRect(0, 0, mSize.width, mSize.height)); MOZ_LOG(gImgLog, LogLevel::Error, ("RasterImage: [this=%p] Error detected for image\n", this)); }
Future<Nothing> connect(const Socket& socket) { // Now check that a successful connection was made. int opt; socklen_t optlen = sizeof(opt); int s = socket.get(); // NOTE: We cast to `char*` here because the function prototypes on Windows // use `char*` instead of `void*`. if (::getsockopt( s, SOL_SOCKET, SO_ERROR, reinterpret_cast<char*>(&opt), &optlen) < 0 || opt != 0) { // Connect failure. VLOG(1) << "Socket error while connecting"; return Failure("Socket error while connecting"); } return Nothing(); }
Future<Nothing> acquire() { if (!promises.empty()) { // Need to wait for others to get permits first. Promise<Nothing>* promise = new Promise<Nothing>(); promises.push_back(promise); return promise->future() .onDiscard(defer(self(), &Self::discard, promise->future())); } if (timeout.remaining() > Seconds(0)) { // Need to wait a bit longer, but first one in the queue. Promise<Nothing>* promise = new Promise<Nothing>(); promises.push_back(promise); delay(timeout.remaining(), self(), &Self::_acquire); return promise->future() .onDiscard(defer(self(), &Self::discard, promise->future())); } // No need to wait! timeout = Seconds(1) / permitsPerSecond; return Nothing(); }
Try<Nothing> createTestFile( const Path& file, const Option<Path>& directory = None()) { const Path testFile( directory.isSome() ? path::join(directory.get(), file.value): file); const string& testFileDir = testFile.dirname(); if (!os::exists(testFileDir)) { Try<Nothing> mkdir = os::mkdir(testFileDir, true); if (mkdir.isError()) { return Error("Failed to create test directory: " + mkdir.error()); } } Try<Nothing> write = os::write(testFile, "test"); if (write.isError()) { return Error("Failed to create to test file: " + write.error()); } return Nothing(); }
// By default, recursively deletes a directory akin to: 'rm -r'. If the // programmer sets recursive to false, it deletes a directory akin to: 'rmdir'. // Note that this function expects an absolute path. inline Try<Nothing> rmdir(const std::string& directory, bool recursive = true) { // Canonicalize the path to Windows style for the call to // `recursive_remove_directory`. Result<std::string> root = os::realpath(directory); if (root.isError()) { return Error(root.error()); } else if (root.isNone()) { return Error( "Argument to `os::rmdir` is not a valid directory or file: '" + directory + "'"); } if (!recursive) { if (::_rmdir(directory.c_str()) < 0) { return ErrnoError(); } else { return Nothing(); } } else { return os::internal::recursive_remove_directory(root.get()); } }
Try<Nothing> copyFromLocal( const std::string& from, std::string to) { if (!os::exists(from)) { return Error("Failed to find " + from); } to = absolutePath(to); // Copy to HDFS. Try<std::string> command = strings::format( "%s fs -copyFromLocal '%s' '%s'", hadoop, from, to); CHECK_SOME(command); Try<std::string> out = os::shell(command.get()); if (out.isError()) { return Error(out.error()); } return Nothing(); }
VectorImage::GetFrameAtSize(const IntSize& aSize, uint32_t aWhichFrame, uint32_t aFlags) { MOZ_ASSERT(aWhichFrame <= FRAME_MAX_VALUE); if (aSize.IsEmpty()) { return nullptr; } if (aWhichFrame > FRAME_MAX_VALUE) { return nullptr; } if (mError || !mIsFullyLoaded) { return nullptr; } // Make our surface the size of what will ultimately be drawn to it. // (either the full image size, or the restricted region) RefPtr<DrawTarget> dt = gfxPlatform::GetPlatform()-> CreateOffscreenContentDrawTarget(aSize, SurfaceFormat::B8G8R8A8); if (!dt || !dt->IsValid()) { NS_ERROR("Could not create a DrawTarget"); return nullptr; } RefPtr<gfxContext> context = gfxContext::CreateOrNull(dt); MOZ_ASSERT(context); // already checked the draw target above auto result = Draw(context, aSize, ImageRegion::Create(aSize), aWhichFrame, SamplingFilter::POINT, Nothing(), aFlags, 1.0); return result == DrawResult::SUCCESS ? dt->Snapshot() : nullptr; }