-
Function `DetectGPUVendors` has a Cognitive Complexity of 30 (exceeds 20 allowed). Consider refactoring.
} func DetectGPUVendors() ([]GPUVendor, error) { var vendors []GPUVendor gpu, err := ghw.GPU() if err != nil { return nil, err } for _, card := range gpu.GraphicsCards { deviceInfo := card.DeviceInfo if deviceInfo != nil { class := deviceInfo.Class if class != nil { className := strings.ToLower(class.Name)
Details
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Found in dms/resources/gpudetect.go by structure -
Avoid deeply nested control flow statements.
vendor := card.DeviceInfo.Vendor if vendor != nil { if strings.Contains(strings.ToLower(vendor.Name), "nvidia") { vendors = append(vendors, NVIDIA) } if strings.Contains(strings.ToLower(vendor.Name), "amd") { vendors = append(vendors, AMD)
Found in dms/resources/gpudetect.go by structure -
Avoid deeply nested control flow statements.
vendors = append(vendors, NVIDIA) } if strings.Contains(strings.ToLower(vendor.Name), "amd") { vendors = append(vendors, AMD) } } }
Found in dms/resources/gpudetect.go by structure -
Function `Check_gpu` has a Cognitive Complexity of 26 (exceeds 20 allowed). Consider refactoring.
) func Check_gpu() ([]models.Gpu, error) { var gpu_info []models.Gpu vendors, err := DetectGPUVendors() if err != nil { return nil, fmt.Errorf("unable to detect GPU Vendor: %v", err) } foundNVIDIA, foundAMD := false, false for _, vendor := range vendors { switch vendor { case NVIDIA: if !foundNVIDIA { var gpu models.Gpu info, err := GetNVIDIAGPUInfo()
Details
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Found in dms/resources/linux_amd64_gpu.go by structure -
Function `calcFreeResources` has 5 return statements (exceeds 4 allowed).
// by the user and the sum of resources usage for every services, virtual machines, plugins // and any other process started by DMS on the user's machine. func calcFreeResources(gormDB *gorm.DB, cpuInfo []cpu.InfoStat) (models.FreeResources, error) { vms, err := queryRunningVMs(gormDB) if err != nil { return models.FreeResources{}, fmt.Errorf("Error querying running VMs: %w", err) } conts, err := queryRunningConts(gormDB) if err != nil { return models.FreeResources{}, fmt.Errorf("Error querying running containers: %w", err) }
Found in dms/resources/calc_resources.go by structure -
Function `GetAMDGPUInfo` has 5 return statements (exceeds 4 allowed).
} func GetAMDGPUInfo() ([]GPUInfo, error) { cmd := exec.Command("rocm-smi", "--showid", "--showproductname", "--showmeminfo", "vram") output, err := cmd.CombinedOutput() if err != nil { return nil, fmt.Errorf("AMD ROCm not installed, initialized, or configured (reboot recommended for newly installed AMD GPU Drivers): %s", err) } outputStr := string(output) gpuName := regexp.MustCompile(`Card series:\s+([^\n]+)`) total := regexp.MustCompile(`Total Memory \(B\):\s+(\d+)`) used := regexp.MustCompile(`Total Used Memory \(B\):\s+(\d+)`)
Found in dms/resources/linux_amd64_gpuinfo.go by structure -
Function `GetNVIDIAGPUInfo` has 6 return statements (exceeds 4 allowed).
} func GetNVIDIAGPUInfo() ([]GPUInfo, error) { // Initialize NVML ret := nvml.Init() if ret != nvml.SUCCESS { return nil, fmt.Errorf("NVIDIA Management Library not installed, initialized or configured (reboot recommended for newly installed NVIDIA GPU drivers): %s", nvml.ErrorString(ret)) } defer nvml.Shutdown() // Get the number of GPU devices deviceCount, ret := nvml.DeviceGetCount() if ret != nvml.SUCCESS { return nil, fmt.Errorf("failed to get device count: %s", nvml.ErrorString(ret)) }
Found in dms/resources/linux_amd64_gpuinfo.go by structure -
Function `Onboard` has 86 lines of code (exceeds 50 allowed). Consider refactoring.
} func Onboard(ctx context.Context, capacity models.CapacityForNunet) (*models.Metadata, error) { configPath := config.GetConfig().General.MetadataPath configExist, err := AFS.DirExists(configPath) if err != nil { return nil, fmt.Errorf("could not check if config directory exists: %w", err) } if !configExist { return nil, fmt.Errorf("config directory does not exist: %w", err) } hostname, _ := os.Hostname() totalCpu := resources.GetTotalProvisioned().CPU
Found in dms/onboarding/handler.go by structure -
Function `Onboard` has 11 return statements (exceeds 4 allowed).
} func Onboard(ctx context.Context, capacity models.CapacityForNunet) (*models.Metadata, error) { configPath := config.GetConfig().General.MetadataPath configExist, err := AFS.DirExists(configPath) if err != nil { return nil, fmt.Errorf("could not check if config directory exists: %w", err) } if !configExist { return nil, fmt.Errorf("config directory does not exist: %w", err) } hostname, _ := os.Hostname() totalCpu := resources.GetTotalProvisioned().CPU
Found in dms/onboarding/handler.go by structure -
Function `ResourceConfig` has 8 return statements (exceeds 4 allowed).
} func ResourceConfig(ctx context.Context, capacity models.CapacityForNunet) (*models.Metadata, error) { onboarded, err := utils.IsOnboarded() if err != nil { return nil, fmt.Errorf("could not check onboard status: %w", err) } if !onboarded { return nil, fmt.Errorf("machine is not onboarded") } err = validateCapacityForNunet(capacity) if err != nil { return nil, fmt.Errorf("could not validate capacity data: %w", err) }
Found in dms/onboarding/handler.go by structure -
Function `Offboard` has 6 return statements (exceeds 4 allowed).
} func Offboard(ctx context.Context, force bool) error { onboarded, err := utils.IsOnboarded() if err != nil && !force { return fmt.Errorf("could not retrieve onboard status: %w", err) } else if err != nil && force { zlog.Sugar().Errorf("problem with onboarding state: %v", err) zlog.Info("continuing with offboarding because forced") } if !onboarded { return fmt.Errorf("machine is not onboarded") }
Found in dms/onboarding/handler.go by structure -
Function `GpuComparator` has 6 return statements (exceeds 4 allowed).
) func GpuComparator(l, r interface{}, preference ...Preference) models.Comparison { // comparator for GPU type // we want to reason about the inner fields of the GPU type and how they compare between left and right // in the future we may want to pass custom preference parameters to the ComplexComparator // for now it is probably best to hardcode them; // validate input type _, lok := l.(models.GPU) _, rok := r.(models.GPU) if !lok || !rok { return models.Error }
Found in dms/orchestrator/matching/GpuComparator.go by structure -
Function `LocalitiesComparator` has 5 return statements (exceeds 4 allowed).
) func LocalitiesComparator(lraw interface{}, rraw interface{}, preference ...Preference) models.Comparison { // simplified version of Localities comparator // which is simply a slice of Locality type; // we do not have separate type defined for Localities // it takes preference variable where comparison Preference is defined // this is the first method that is used to take Preference variable into account // left represent machine capabilities; // right represent required capabilities; // validate input type _, lrawok := lraw.([]models.Locality) _, rrawok := rraw.([]models.Locality) if !lrawok || !rrawok {
Found in dms/orchestrator/matching/LocalitiesComparator.go by structure -
Function `GPUsComparator` has 5 return statements (exceeds 4 allowed).
) func GPUsComparator(lraw, rraw interface{}, preference ...Preference) models.Comparison { // comparator for GPUs type which is just a slice of GPU types: // left represent machine capabilities; // right represent required capabilities; // we need to check if for ech GPU on the right there exist a matching GPU on the left... // (since given slices are not ordered...) // validate input type _, lrawok := lraw.([]models.GPU) _, rrawok := rraw.([]models.GPU) if !lrawok || !rrawok { return models.Error }
Found in dms/orchestrator/matching/GPUsComparator.go by structure -
Function `LibraryComparator` has 7 return statements (exceeds 4 allowed).
) func LibraryComparator(lraw, rraw interface{}, preference ...Preference) models.Comparison { // comparator for single Library type: // left represent machine capabilities; // right represent required capabilities; // validate input type _, lrawok := lraw.(models.Library) _, rrawok := rraw.(models.Library) if !lrawok || !rrawok { return models.Error } l := lraw.(models.Library)
Found in dms/orchestrator/matching/LibraryComparator.go by structure -
Function `LibrariesComparator` has 5 return statements (exceeds 4 allowed).
) func LibrariesComparator(lraw, rraw interface{}, preference ...Preference) models.Comparison { // comparator for Libraries slices (of different lengths) of Library types: // left represent machine capabilities; // right represent required capabilities; // validate input type _, lrawok := lraw.([]models.Library) _, rrawok := rraw.([]models.Library) if !lrawok || !rrawok { return models.Error } l := lraw.([]models.Library)
Found in dms/orchestrator/matching/LibrariesComparator.go by structure -
Function `ExecutionResourcesComparator` has 5 return statements (exceeds 4 allowed).
) func ExecutionResourcesComparator(l, r interface{}, preference ...Preference) models.Comparison { // comparator for models.ExecutionResources type // Current implementation of the type has four fields: CPU, Memory, Disk, GPUs // we consider that all fields have to be 'Better' or 'Equal' // for the comparison to be 'Better' or 'Equal' // else we return 'Worse' // validate input type _, lok := l.(models.ExecutionResources) _, rok := r.(models.ExecutionResources) if !lok || !rok { return models.Error }
Found in dms/orchestrator/matching/ExecutionResourcesComparator.go by structure -
Function `returnBestMatch` has 5 return statements (exceeds 4 allowed).
} func returnBestMatch(dimension []models.Comparison) (models.Comparison, int) { // while i feel that there could be some weird matrix sorting algorithm that could be used here // i can't think of any right now, so i will just iterate over the matrix and return matches // in somewhat manual way for i, v := range dimension { if v == models.Equal { return v, i // selecting an equal match is the most efficient match } } for i, v := range dimension { if v == models.Better {
Found in dms/orchestrator/matching/utils.go by structure -
Function `newActor` has 5 arguments (exceeds 4 allowed). Consider refactoring.
// newActor returns a new actor based on the given arguments. func newActor(parentActorAddress *ActorAddrInfo, hostID string, net network.Network, actorRegistry *ActorRegistry, factory *ActorFactory) (*Actor, error) { if hostID == "" { return nil, errors.New("host id is empty")
Found in dms/actor.go by structure -
Method `Actor.SendMessage` has 5 return statements (exceeds 4 allowed).
// SendMessage sends a message to another actor. func (a *Actor) SendMessage(ctx context.Context, destination *ActorAddrInfo, m *Message) error { if !destination.Valid() { return errors.New("destination actor addr info is invalid") } if m == nil { return errors.New("message is invalid") } // get the multiaddress of a host by resolving the hostid addresses, err := a.network.ResolveAddress(ctx, destination.HostID) if err != nil { return fmt.Errorf("failed to send message to actor %s: %v", destination.HostID, err)
Found in dms/actor.go by structure -
Function `MakeRequest` has 5 arguments (exceeds 4 allowed). Consider refactoring.
} func MakeRequest(c *gin.Context, client *http.Client, uri string, body []byte, errMsg string) error { // set the HTTP method, url, and request body req, err := http.NewRequest(http.MethodPut, uri, bytes.NewBuffer(body))
Found in utils/network.go by structure -
Function `ExtractTarGzToPath` has a Cognitive Complexity of 23 (exceeds 20 allowed). Consider refactoring.
// ExtractTarGzToPath extracts a tar.gz file to a specified path func ExtractTarGzToPath(tarGzFilePath, extractedPath string) error { // Ensure the target directory exists; create it if it doesn't. if err := os.MkdirAll(extractedPath, os.ModePerm); err != nil { return fmt.Errorf("error creating target directory: %v", err) } tarGzFile, err := os.Open(tarGzFilePath) if err != nil { return fmt.Errorf("error opening tar.gz file: %v", err) } defer tarGzFile.Close() gzipReader, err := gzip.NewReader(tarGzFile)
Details
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Found in utils/utils.go by structure -
Function `ExtractTarGzToPath` has 9 return statements (exceeds 4 allowed).
// ExtractTarGzToPath extracts a tar.gz file to a specified path func ExtractTarGzToPath(tarGzFilePath, extractedPath string) error { // Ensure the target directory exists; create it if it doesn't. if err := os.MkdirAll(extractedPath, os.ModePerm); err != nil { return fmt.Errorf("error creating target directory: %v", err) } tarGzFile, err := os.Open(tarGzFilePath) if err != nil { return fmt.Errorf("error opening tar.gz file: %v", err) } defer tarGzFile.Close() gzipReader, err := gzip.NewReader(tarGzFile)
Found in utils/utils.go by structure -
File `docs.go` has 888 lines of code (exceeds 500 allowed). Consider refactoring.
// Package docs Code generated by swaggo/swag. DO NOT EDIT package docs import "github.com/swaggo/swag" const docTemplate = `{ "schemes": {{ marshal .Schemes }}, "swagger": "2.0", "info": { "description": "{{escape .Description}}", "title": "{{.Title}}", "termsOfService": "https://nunet.io/tos", "contact": {
Found in api/docs/docs.go by structure -
Method `dhtValidator.Validate` has 7 return statements (exceeds 4 allowed).
// Validate validates an item placed into the dht. func (d dhtValidator) Validate(key string, value []byte) error { // empty value is considered deleting an item from the dht if len(value) == 0 { return nil } if !strings.HasPrefix(key, d.customNamespace) { return errors.New("invalid key namespace") } // verify signature var envelope commonproto.Advertisement err := proto.Unmarshal(value, &envelope)
Found in network/libp2p/dht.go by structure -
File `libp2p.go` has 533 lines of code (exceeds 500 allowed). Consider refactoring.
package libp2p import ( "context" "bufio" "bytes" "crypto/sha256" "encoding/binary" "errors" "fmt" "io" "strings"
Found in network/libp2p/libp2p.go by structure -
`Libp2p` has 28 methods (exceeds 20 allowed). Consider refactoring.
// TODO-suggestion: maybe we should call it something else like Libp2pPeer, // Libp2pHost or just Peer (callers would use libp2p.Peer...) type Libp2p struct { Host host.Host DHT *dht.IpfsDHT PS peerstore.Peerstore pubsub *pubsub.PubSub pubsubTopics map[string]*pubsub.Topic topicSubscription map[string]*pubsub.Subscription topicMux sync.RWMutex // a list of peers discovered by discovery discoveredPeers []peer.AddrInfo discovery libp2pdiscovery.Discovery
Found in network/libp2p/libp2p.go by structure -
Method `Libp2p.OpenStream` has 5 return statements (exceeds 4 allowed).
// OpenStream opens a stream to a remote address and returns the stream for the caller to handle. func (l *Libp2p) OpenStream(ctx context.Context, addr string, messageType models.MessageType) (network.Stream, error) { maddr, err := multiaddr.NewMultiaddr(addr) if err != nil { return nil, fmt.Errorf("invalid multiaddress: %w", err) } peerInfo, err := peer.AddrInfoFromP2pAddr(maddr) if err != nil { return nil, fmt.Errorf("could not resolve peer info: %w", err) } if err := l.Host.Connect(ctx, *peerInfo); err != nil { return nil, fmt.Errorf("failed to connect to peer: %w", err)
Found in network/libp2p/libp2p.go by structure -
Method `Libp2p.Ping` has 5 return statements (exceeds 4 allowed).
// TODO (Return error once): something that was confusing me when using this method is that the error is // returned twice if any. Once as a field of PingResult and one as a return value. func (l *Libp2p) Ping(ctx context.Context, peerIDAddress string, timeout time.Duration) (models.PingResult, error) { // avoid dial to self attempt if peerIDAddress == l.Host.ID().String() { err := errors.New("can't ping self") return models.PingResult{Success: false, Error: err}, err } pingCtx, cancel := context.WithTimeout(ctx, timeout) defer cancel() remotePeer, err := peer.Decode(peerIDAddress) if err != nil { return models.PingResult{}, err
Found in network/libp2p/libp2p.go by structure -
Method `Libp2p.ResolveAddress` has 6 return statements (exceeds 4 allowed).
// ResolveAddress resolves the address by given a peer id. func (l *Libp2p) ResolveAddress(ctx context.Context, id string) ([]string, error) { pid, err := peer.Decode(id) if err != nil { return nil, fmt.Errorf("failed to resolve invalid peer: %w", err) } // resolve ourself if l.Host.ID().String() == id { multiAddrs, err := l.GetMultiaddr() if err != nil { return nil, fmt.Errorf("failed to resolve self: %w", err) } resolved := make([]string, len(multiAddrs))
Found in network/libp2p/libp2p.go by structure -
Method `Libp2p.Query` has 5 return statements (exceeds 4 allowed).
// Query return all the advertisements in the network related to a key. // The network is queried to find providers for the given key, and peers which we aren't connected to can be retrieved. func (l *Libp2p) Query(ctx context.Context, key string) ([]*commonproto.Advertisement, error) { if key == "" { return nil, errors.New("advertisement key is empty") } customCID, err := createCIDFromKey(key) if err != nil { return nil, fmt.Errorf("failed to create cid for key %s: %w", key, err) } addrInfo, err := l.DHT.FindProviders(ctx, customCID) if err != nil { return nil, fmt.Errorf("failed to find providers for key %s: %w", key, err)
Found in network/libp2p/libp2p.go by structure -
Method `Libp2p.Advertise` has 8 return statements (exceeds 4 allowed).
// Advertise given data and a key pushes the data to the dht. func (l *Libp2p) Advertise(ctx context.Context, key string, data []byte) error { if key == "" { return errors.New("advertisement key is empty") } pubKeyBytes, err := l.getPublicKey() if err != nil { return fmt.Errorf("failed to get public key: %w", err) } envelope := &commonproto.Advertisement{ PeerId: l.Host.ID().String(), Timestamp: time.Now().Unix(),
Found in network/libp2p/libp2p.go by structure -
Method `Libp2p.sendMessage` has 8 return statements (exceeds 4 allowed).
} func (l *Libp2p) sendMessage(ctx context.Context, addr string, msg models.MessageEnvelope) error { peerAddr, err := multiaddr.NewMultiaddr(addr) if err != nil { return fmt.Errorf("invalid multiaddr %s: %v", addr, err) } peerInfo, err := peer.AddrInfoFromP2pAddr(peerAddr) if err != nil { return fmt.Errorf("failed to get peer info %s: %v", addr, err) } // we are delivering a message to ourself // we should use the handler to send the message to the handler directly which has been previously registered.
Found in network/libp2p/libp2p.go by structure -
Function `generateSwarmKey` has 6 return statements (exceeds 4 allowed).
// generateSwarmKey generates a new swarm key, storing it within // `<nunet_config_dir>/swarm.key`. func generateSwarmKey(fs afero.Fs) (pnet.PSK, error) { priv, _, err := crypto.GenerateKeyPair(crypto.Secp256k1, 256) if err != nil { return nil, err } privBytes, err := crypto.MarshalPrivateKey(priv) if err != nil { return nil, err } encodedKey := base64.StdEncoding.EncodeToString(privBytes) swarmKeyWithCodec := fmt.Sprintf("/key/swarm/psk/1.0.0/\n/base64/\n%s\n", encodedKey)
Found in network/libp2p/pnet.go by structure -
Function `makeAddrsFactory` has a Cognitive Complexity of 22 (exceeds 20 allowed). Consider refactoring.
} func makeAddrsFactory(announce []string, appendAnnouce []string, noAnnounce []string) func([]multiaddr.Multiaddr) []multiaddr.Multiaddr { var err error // To assign to the slice in the for loop existing := make(map[string]bool) // To avoid duplicates annAddrs := make([]multiaddr.Multiaddr, len(announce)) for i, addr := range announce { annAddrs[i], err = multiaddr.NewMultiaddr(addr) if err != nil { return nil } existing[addr] = true }
Details
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Found in network/libp2p/filter.go by structure -
Function `makeAddrsFactory` has 52 lines of code (exceeds 50 allowed). Consider refactoring.
} func makeAddrsFactory(announce []string, appendAnnouce []string, noAnnounce []string) func([]multiaddr.Multiaddr) []multiaddr.Multiaddr { var err error // To assign to the slice in the for loop existing := make(map[string]bool) // To avoid duplicates annAddrs := make([]multiaddr.Multiaddr, len(announce)) for i, addr := range announce { annAddrs[i], err = multiaddr.NewMultiaddr(addr) if err != nil { return nil } existing[addr] = true }
Found in network/libp2p/filter.go by structure -
Function `NewHost` has a Cognitive Complexity of 25 (exceeds 20 allowed). Consider refactoring.
// NewHost returns a new libp2p host with dht and other related settings. func NewHost(ctx context.Context, config *models.Libp2pConfig, fs afero.Fs) (host.Host, *dht.IpfsDHT, *pubsub.PubSub, error) { var idht *dht.IpfsDHT connmgr, err := connmgr.NewConnManager( 100, 400, connmgr.WithGracePeriod(time.Duration(config.GracePeriodMs)*time.Millisecond), ) if err != nil { return nil, nil, nil, err } filter := multiaddr.NewFilters() for _, s := range defaultServerFilters {
Details
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Found in network/libp2p/host.go by structure -
Function `NewHost` has 112 lines of code (exceeds 50 allowed). Consider refactoring.
// NewHost returns a new libp2p host with dht and other related settings. func NewHost(ctx context.Context, config *models.Libp2pConfig, fs afero.Fs) (host.Host, *dht.IpfsDHT, *pubsub.PubSub, error) { var idht *dht.IpfsDHT connmgr, err := connmgr.NewConnManager( 100, 400, connmgr.WithGracePeriod(time.Duration(config.GracePeriodMs)*time.Millisecond), ) if err != nil { return nil, nil, nil, err } filter := multiaddr.NewFilters() for _, s := range defaultServerFilters {
Found in network/libp2p/host.go by structure -
Function `NewHost` has 10 return statements (exceeds 4 allowed).
// NewHost returns a new libp2p host with dht and other related settings. func NewHost(ctx context.Context, config *models.Libp2pConfig, fs afero.Fs) (host.Host, *dht.IpfsDHT, *pubsub.PubSub, error) { var idht *dht.IpfsDHT connmgr, err := connmgr.NewConnManager( 100, 400, connmgr.WithGracePeriod(time.Duration(config.GracePeriodMs)*time.Millisecond), ) if err != nil { return nil, nil, nil, err } filter := multiaddr.NewFilters() for _, s := range defaultServerFilters {
Found in network/libp2p/host.go by structure -
Method `S3Storage.Download` has 6 return statements (exceeds 4 allowed).
// be careful if managing files with `os` (the volume controller might be // using an in-memory one) func (s *S3Storage) Download(ctx context.Context, sourceSpecs *models.SpecConfig) ( models.StorageVolume, error) { var storageVol models.StorageVolume source, err := DecodeInputSpec(sourceSpecs) if err != nil { return models.StorageVolume{}, err } storageVol, err = s.volController.CreateVolume(storage.VolumeSourceS3) if err != nil { return models.StorageVolume{}, fmt.Errorf("failed to create storage volume: %v", err) }
Found in storage/s3/download.go by structure -
Method `S3Storage.Upload` has 9 return statements (exceeds 4 allowed).
// be careful if managing files with `os` (the volume controller might be // using an in-memory one) func (s *S3Storage) Upload(ctx context.Context, vol models.StorageVolume, destinationSpecs *models.SpecConfig) error { target, err := DecodeInputSpec(destinationSpecs) if err != nil { return fmt.Errorf("failed to decode input spec: %v", err) } sanitizedKey := sanitizeKey(target.Key) // set file system to act upon based on the volume controller implementation var fs afero.Fs if basicVolController, ok := s.volController.(*basic_controller.BasicVolumeController); ok {
Found in storage/s3/upload.go by structure -
Function `SetupVolControllerTestSuite` has 7 return statements (exceeds 4 allowed).
// SetupVolControllerTestSuite sets up a volume controller with 0-n volumes given a base path. // If volumes are inputed, directories will be created and volumes will be stored in the database func SetupVolControllerTestSuite(t *testing.T, basePath string, volumes map[string]*models.StorageVolume) (*VolControllerTestSuiteHelper, error) { tempDir, err := os.MkdirTemp("", "clover-test-*") if err != nil { return nil, fmt.Errorf("failed to create temp directory: %w", err) } db, err := repositories_clover.NewDB(tempDir, []string{"storage_volume"}) if err != nil { os.RemoveAll(tempDir) return nil, fmt.Errorf("failed to open clover db: %w", err) }
Found in storage/basic_controller/test_suite.go by structure -
Method `Capability.Add` has a Cognitive Complexity of 33 (exceeds 20 allowed). Consider refactoring.
// Add adds the resources of the given Capability to the current Capability func (c *Capability) Add(cap Capability) error { // Executors for _, executor := range cap.Executors { if !c.Executors.Contains(executor) { c.Executors = append(c.Executors, executor) } } // JobTypes for _, jobType := range cap.JobTypes { if !c.JobTypes.Contains(jobType) { c.JobTypes = append(c.JobTypes, jobType) }
Details
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Found in models/capability.go by structure -
Method `Capability.Subtract` has a Cognitive Complexity of 23 (exceeds 20 allowed). Consider refactoring.
// Subtract subtracts the resources of the given Capability from the current Capability func (c *Capability) Subtract(cap Capability) error { // Executors // No Subtract operation for Executors // JobTypes // No Subtract operation for JobTypes // Resources if c.Resources.CPU < cap.Resources.CPU { return errors.New("CPU resources are not enough") } if c.Resources.Memory < cap.Resources.Memory {
Details
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Found in models/capability.go by structure -
Method `Capability.Add` has 66 lines of code (exceeds 50 allowed). Consider refactoring.
// Add adds the resources of the given Capability to the current Capability func (c *Capability) Add(cap Capability) error { // Executors for _, executor := range cap.Executors { if !c.Executors.Contains(executor) { c.Executors = append(c.Executors, executor) } } // JobTypes for _, jobType := range cap.JobTypes { if !c.JobTypes.Contains(jobType) { c.JobTypes = append(c.JobTypes, jobType) }
Found in models/capability.go by structure -
Method `GPU.Equal` has 7 return statements (exceeds 4 allowed).
} func (g *GPU) Equal(gg *GPU) bool { if g.Index != gg.Index { return false } if g.Name != gg.Name { return false } if g.Vendor != gg.Vendor { return false } if g.PCIAddress != gg.PCIAddress { return false }
Found in models/resource.go by structure -
Method `Client.CreateContainer` has 6 arguments (exceeds 4 allowed). Consider refactoring.
// CreateContainer creates a new Docker container with the specified configuration. func (c *Client) CreateContainer( ctx context.Context, config *container.Config, hostConfig *container.HostConfig, networkingConfig *network.NetworkingConfig, platform *v1.Platform, name string, ) (string, error) { _, err := c.PullImage(ctx, config.Image)
Found in executor/docker/client.go by structure -
Function `DecodeSpec` has 5 return statements (exceeds 4 allowed).
// DecodeSpec decodes a spec config into a docker engine spec // It converts the params into a docker EngineSpec struct and validates it func DecodeSpec(spec *models.SpecConfig) (EngineSpec, error) { if !spec.IsType(models.ExecutorTypeDocker) { return EngineSpec{}, fmt.Errorf( "invalid docker engine type. expected %s, but recieved: %s", models.ExecutorTypeDocker, spec.Type, ) } inputParams := spec.Params if inputParams == nil { return EngineSpec{}, fmt.Errorf("invalid docker engine params: params cannot be nil") }
Found in executor/docker/types.go by structure -
Method `executionHandler.run` has 71 lines of code (exceeds 50 allowed). Consider refactoring.
// run starts the container and handles its execution lifecycle. func (h *executionHandler) run(ctx context.Context) { h.running.Store(true) defer func() { if err := h.destroy(DestroyTimeout); err != nil { zlog.Sugar().Warnf("failed to destroy container: %v\n", err) } h.running.Store(false) close(h.waitCh) }() if err := h.client.StartContainer(ctx, h.containerID); err != nil { h.result = models.NewFailedExecutionResult(fmt.Errorf("failed to start container: %v", err)) return
Found in executor/docker/handler.go by structure -
Method `executionHandler.run` has 6 return statements (exceeds 4 allowed).
// run starts the container and handles its execution lifecycle. func (h *executionHandler) run(ctx context.Context) { h.running.Store(true) defer func() { if err := h.destroy(DestroyTimeout); err != nil { zlog.Sugar().Warnf("failed to destroy container: %v\n", err) } h.running.Store(false) close(h.waitCh) }() if err := h.client.StartContainer(ctx, h.containerID); err != nil { h.result = models.NewFailedExecutionResult(fmt.Errorf("failed to start container: %v", err)) return
Found in executor/docker/handler.go by structure -
Method `Client.DestroyVM` has 5 return statements (exceeds 4 allowed).
// DestroyVM destroys the Firecracker VM. func (c *Client) DestroyVM( ctx context.Context, m *firecracker.Machine, timeout time.Duration, ) error { // Remove the socket file. defer os.Remove(m.Cfg.SocketPath) // Get the PID of the Firecracker process and shut down the VM. // If the process is still running after the timeout, kill it. pid, _ := m.PID() c.ShutdownVM(ctx, m)
Found in executor/firecracker/client.go by structure -
Method `Client.FindVM` has 5 return statements (exceeds 4 allowed).
// FindVM finds a Firecracker VM by its socket path. // This implementation checks if the VM is running by sending a request to the Firecracker API. func (c *Client) FindVM(ctx context.Context, socketPath string) (*firecracker.Machine, error) { // Check if the socket file exists. if _, err := os.Stat(socketPath); err != nil { return nil, fmt.Errorf("VM with socket path %v not found", socketPath) } // Create a new Firecracker machine instance. cmd := firecracker.VMCommandBuilder{}.WithSocketPath(socketPath).Build(ctx) machine, err := firecracker.NewMachine( ctx, firecracker.Config{SocketPath: socketPath}, firecracker.WithProcessRunner(cmd), )
Found in executor/firecracker/client.go by structure -
Function `DecodeSpec` has 5 return statements (exceeds 4 allowed).
// DecodeSpec decodes a spec config into a firecracker engine spec // It converts the params into a firecracker EngineSpec struct and validates it func DecodeSpec(spec *models.SpecConfig) (EngineSpec, error) { if !spec.IsType(models.ExecutorTypeFirecracker) { return EngineSpec{}, fmt.Errorf( "invalid firecracker engine type. expected %s, but recieved: %s", models.ExecutorTypeFirecracker, spec.Type, ) } inputParams := spec.Params if inputParams == nil { return EngineSpec{}, fmt.Errorf("invalid firecracker engine params: params cannot be nil") }
Found in executor/firecracker/types.go by structure -
Function `NewChatJoinCmd` has 63 lines of code (exceeds 50 allowed). Consider refactoring.
// XXX NewChatJoinCmd and NewChatStartCmd are similar, consider refactoring func NewChatJoinCmd(utilsService backend.Utility, wsClient backend.WebSocketClient) *cobra.Command { return &cobra.Command{ Use: "join", Short: "Join open chat stream", Example: "nunet chat join <chatID>", Long: "", RunE: func(cmd *cobra.Command, args []string) error { chatList, err := utilsService.ResponseBody(nil, "GET", "/api/v1/peers/chat", "", nil) if err != nil { return fmt.Errorf("could not obtain incoming chats list: %w", err) } err = validateJoinChatInput(args, chatList)
Found in cmd/chat_join.go by structure -
Function `NewOnboardCmd` has a Cognitive Complexity of 23 (exceeds 20 allowed). Consider refactoring.
) func NewOnboardCmd(net backend.NetworkManager, utilsService backend.Utility) *cobra.Command { cmd := &cobra.Command{ Use: "onboard", Short: "Onboard current machine to NuNet", PreRunE: isDMSRunning(net), RunE: func(cmd *cobra.Command, args []string) error { memory, _ := cmd.Flags().GetInt64("memory") cpu, _ := cmd.Flags().GetInt64("cpu") channel, _ := cmd.Flags().GetString("nunet-channel") address, _ := cmd.Flags().GetString("address") ntxPrice, _ := cmd.Flags().GetFloat64("ntx-price") local, _ := cmd.Flags().GetBool("local-enable") cardano, _ := cmd.Flags().GetBool("cardano")
Details
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Found in cmd/onboard.go by structure -
Function `NewOnboardCmd` has 65 lines of code (exceeds 50 allowed). Consider refactoring.
) func NewOnboardCmd(net backend.NetworkManager, utilsService backend.Utility) *cobra.Command { cmd := &cobra.Command{ Use: "onboard", Short: "Onboard current machine to NuNet", PreRunE: isDMSRunning(net), RunE: func(cmd *cobra.Command, args []string) error { memory, _ := cmd.Flags().GetInt64("memory") cpu, _ := cmd.Flags().GetInt64("cpu") channel, _ := cmd.Flags().GetString("nunet-channel") address, _ := cmd.Flags().GetString("address") ntxPrice, _ := cmd.Flags().GetFloat64("ntx-price") local, _ := cmd.Flags().GetBool("local-enable") cardano, _ := cmd.Flags().GetBool("cardano")
Found in cmd/onboard.go by structure -
Function `NewOnboardCmd` has 12 return statements (exceeds 4 allowed).
) func NewOnboardCmd(net backend.NetworkManager, utilsService backend.Utility) *cobra.Command { cmd := &cobra.Command{ Use: "onboard", Short: "Onboard current machine to NuNet", PreRunE: isDMSRunning(net), RunE: func(cmd *cobra.Command, args []string) error { memory, _ := cmd.Flags().GetInt64("memory") cpu, _ := cmd.Flags().GetInt64("cpu") channel, _ := cmd.Flags().GetString("nunet-channel") address, _ := cmd.Flags().GetString("address") ntxPrice, _ := cmd.Flags().GetFloat64("ntx-price") local, _ := cmd.Flags().GetBool("local-enable") cardano, _ := cmd.Flags().GetBool("cardano")
Found in cmd/onboard.go by structure -
Function `NewWalletNewCmd` has 5 return statements (exceeds 4 allowed).
) func NewWalletNewCmd(wallet backend.WalletManager) *cobra.Command { cmd := &cobra.Command{ Use: "new", Short: "Create new wallet", RunE: func(cmd *cobra.Command, args []string) error { eth, _ := cmd.Flags().GetBool("ethereum") ada, _ := cmd.Flags().GetBool("cardano") var pair *models.BlockchainAddressPrivKey var err error // limit wallet creation to one at a time if ada && eth {
Found in cmd/wallet_new.go by structure -
Function `NewPeerListCmd` has 5 return statements (exceeds 4 allowed).
) func NewPeerListCmd(utilsService backend.Utility) *cobra.Command { cmd := &cobra.Command{ Use: "list", Short: "Display list of peers in the network", Long: ``, RunE: func(cmd *cobra.Command, args []string) error { err := checkOnboarded(utilsService) if err != nil { return err } dhtFlag, _ := cmd.Flags().GetBool("dht")
Found in cmd/peer_list.go by structure -
Function `NewCapacityCmd` has a Cognitive Complexity of 25 (exceeds 20 allowed). Consider refactoring.
) func NewCapacityCmd(net backend.NetworkManager, resources backend.ResourceManager, utilsService backend.Utility) *cobra.Command { cmd := &cobra.Command{ Use: "capacity", Short: "Display capacity of device resources", Long: `Retrieve capacity of the machine, onboarded or available amount of resources`, PreRunE: isDMSRunning(net), RunE: func(cmd *cobra.Command, args []string) error { onboarded, _ := cmd.Flags().GetBool("onboarded") full, _ := cmd.Flags().GetBool("full") available, _ := cmd.Flags().GetBool("available") // flagCombination stores the bitwise value of combined flags var flagCombination int
Details
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Found in cmd/capacity.go by structure -
Function `NewCapacityCmd` has 51 lines of code (exceeds 50 allowed). Consider refactoring.
) func NewCapacityCmd(net backend.NetworkManager, resources backend.ResourceManager, utilsService backend.Utility) *cobra.Command { cmd := &cobra.Command{ Use: "capacity", Short: "Display capacity of device resources", Long: `Retrieve capacity of the machine, onboarded or available amount of resources`, PreRunE: isDMSRunning(net), RunE: func(cmd *cobra.Command, args []string) error { onboarded, _ := cmd.Flags().GetBool("onboarded") full, _ := cmd.Flags().GetBool("full") available, _ := cmd.Flags().GetBool("available") // flagCombination stores the bitwise value of combined flags var flagCombination int
Found in cmd/capacity.go by structure -
Function `NewCapacityCmd` has 5 return statements (exceeds 4 allowed).
) func NewCapacityCmd(net backend.NetworkManager, resources backend.ResourceManager, utilsService backend.Utility) *cobra.Command { cmd := &cobra.Command{ Use: "capacity", Short: "Display capacity of device resources", Long: `Retrieve capacity of the machine, onboarded or available amount of resources`, PreRunE: isDMSRunning(net), RunE: func(cmd *cobra.Command, args []string) error { onboarded, _ := cmd.Flags().GetBool("onboarded") full, _ := cmd.Flags().GetBool("full") available, _ := cmd.Flags().GetBool("available") // flagCombination stores the bitwise value of combined flags var flagCombination int
Found in cmd/capacity.go by structure -
Function `runDockerContainer` has 56 lines of code (exceeds 50 allowed). Consider refactoring.
} func runDockerContainer(cli *client.Client, ctx context.Context, options ContainerOptions) error { if options.Image == "" { return fmt.Errorf("image name cannot be empty") } config := &container.Config{ Image: options.Image, Entrypoint: options.Entrypoint, Cmd: options.Command, Tty: true, } hostConfig := &container.HostConfig{}
Found in cmd/gpu_capacity.go by structure -
Function `runDockerContainer` has 8 return statements (exceeds 4 allowed).
} func runDockerContainer(cli *client.Client, ctx context.Context, options ContainerOptions) error { if options.Image == "" { return fmt.Errorf("image name cannot be empty") } config := &container.Config{ Image: options.Image, Entrypoint: options.Entrypoint, Cmd: options.Command, Tty: true, } hostConfig := &container.HostConfig{}
Found in cmd/gpu_capacity.go by structure -
Function `NewLogCmd` has a Cognitive Complexity of 29 (exceeds 20 allowed). Consider refactoring.
var logCmd *cobra.Command func NewLogCmd(net backend.NetworkManager, fs backend.FileSystem, journal backend.Logger) *cobra.Command { return &cobra.Command{ Use: "log", Short: "Gather all logs into a tarball. COMMAND MUST RUN AS ROOT WITH SUDO", PreRunE: isDMSRunning(net), RunE: func(cmd *cobra.Command, args []string) error { dmsLogDir := filepath.Join(logDir, "dms-log") fmt.Fprintln(cmd.OutOrStdout(), "Collecting logs...") err := fs.MkdirAll(dmsLogDir, 0777) if err != nil { return fmt.Errorf("cannot create dms-log directory: %w", err)
Details
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Found in cmd/log_linux.go by structure -
Function `NewLogCmd` has 64 lines of code (exceeds 50 allowed). Consider refactoring.
var logCmd *cobra.Command func NewLogCmd(net backend.NetworkManager, fs backend.FileSystem, journal backend.Logger) *cobra.Command { return &cobra.Command{ Use: "log", Short: "Gather all logs into a tarball. COMMAND MUST RUN AS ROOT WITH SUDO", PreRunE: isDMSRunning(net), RunE: func(cmd *cobra.Command, args []string) error { dmsLogDir := filepath.Join(logDir, "dms-log") fmt.Fprintln(cmd.OutOrStdout(), "Collecting logs...") err := fs.MkdirAll(dmsLogDir, 0777) if err != nil { return fmt.Errorf("cannot create dms-log directory: %w", err)
Found in cmd/log_linux.go by structure -
Function `NewResourceConfigCmd` has 7 return statements (exceeds 4 allowed).
var resourceConfigCmd = NewResourceConfigCmd(networkService, utilsService) func NewResourceConfigCmd(net backend.NetworkManager, utilsService backend.Utility) *cobra.Command { cmd := &cobra.Command{ Use: "resource-config", Short: "Update configuration of onboarded device", PreRunE: isDMSRunning(net), RunE: func(cmd *cobra.Command, args []string) error { memory, _ := cmd.Flags().GetInt64("memory") cpu, _ := cmd.Flags().GetInt64("cpu") ntxPrice, _ := cmd.Flags().GetFloat64("ntx-price") // check for both flags values if memory == 0 || cpu == 0 || ntxPrice < 0 { cmd.Help()
Found in cmd/resource-config.go by structure -
Function `NewChatStartCmd` has 58 lines of code (exceeds 50 allowed). Consider refactoring.
var chatStartCmd = NewChatStartCmd(p2pService, utilsService, webSocketClient) func NewChatStartCmd(p2pService backend.PeerManager, utilsService backend.Utility, wsClient backend.WebSocketClient) *cobra.Command { return &cobra.Command{ Use: "start", Short: "Start chat with a peer", Example: "nunet chat start <peerID>", RunE: func(cmd *cobra.Command, args []string) error { log.SetOutput(cmd.OutOrStderr()) err := validateStartChatInput(p2pService, args) if err != nil { return fmt.Errorf("start chat failed: %w", err) }
Found in cmd/chat_start.go by structure -
Avoid deeply nested control flow statements.
for { select { case <-exit: fmt.Println("signal: interrupt") return default: // clear screen (not reliable, maybe implement something ncurses-like for future) fmt.Print("\033[H\033[2J") fmt.Println("========== NuNet GPU Status ==========") fmt.Println("========== GPU Utilization ==========") for _, a := range amdGPUs { fmt.Printf("%d AMD %s: %d%%\n", a.index, a.name(), a.utilizationRate()) }
Found in cmd/gpu_status.go by structure -
Function `setOnboardData` has 5 arguments (exceeds 4 allowed). Consider refactoring.
// setOnboardData takes all onboarding parameters and marshal them into JSON func setOnboardData(memory int64, cpu int64, ntxPrice float64, channel, address string, cardano, serverMode, isAvailable bool) ([]byte, error) { reserved := models.CapacityForNunet{ Memory: memory,
Found in cmd/utils.go by structure -
Function `printMetadata` has a Cognitive Complexity of 39 (exceeds 20 allowed). Consider refactoring.
// printMetadata takes models.Metadata struct as input and display it in YAML-like format for better readability func printMetadata(w io.Writer, metadata *models.Metadata) { fmt.Fprintln(w, "metadata:") if metadata.Name != "" { fmt.Fprintf(w, " name: %s\n", metadata.Name) } if metadata.UpdateTimestamp != 0 { fmt.Fprintf(w, " update_timestamp: %d\n", metadata.UpdateTimestamp) } if metadata.Resource.MemoryMax != 0 || metadata.Resource.TotalCore != 0 || metadata.Resource.CPUMax != 0 { fmt.Fprintln(w, " resource:")
Details
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Found in cmd/utils.go by structure -
Function `printMetadata` has 67 lines of code (exceeds 50 allowed). Consider refactoring.
// printMetadata takes models.Metadata struct as input and display it in YAML-like format for better readability func printMetadata(w io.Writer, metadata *models.Metadata) { fmt.Fprintln(w, "metadata:") if metadata.Name != "" { fmt.Fprintf(w, " name: %s\n", metadata.Name) } if metadata.UpdateTimestamp != 0 { fmt.Fprintf(w, " update_timestamp: %d\n", metadata.UpdateTimestamp) } if metadata.Resource.MemoryMax != 0 || metadata.Resource.TotalCore != 0 || metadata.Resource.CPUMax != 0 { fmt.Fprintln(w, " resource:")
Found in cmd/utils.go by structure -
Function `validateJoinChatInput` has 6 return statements (exceeds 4 allowed).
// END func validateJoinChatInput(args []string, chatList []byte) error { var chatID int var err error if len(args) == 0 || args[0] == "" { return fmt.Errorf("no chat ID specified") } else if len(args) > 1 { return fmt.Errorf("unable to join multiple chats") } else { chatID, err = strconv.Atoi(args[0]) if err != nil { return fmt.Errorf("argument is not integer") }
Found in cmd/utils.go by structure -
Function `getDHTPeers` has 6 return statements (exceeds 4 allowed).
// getDHTPeers fetches API to retrieve info from DHT peers func getDHTPeers(utilsService backend.Utility) ([]string, error) { var dhtSlice []string bodyDht, err := utilsService.ResponseBody(nil, "GET", "/api/v1/peers/dht", "", nil) if err != nil { return nil, fmt.Errorf("cannot get response body: %w", err) } errMsg, err := jsonparser.GetString(bodyDht, "error") if err == nil { return nil, fmt.Errorf(errMsg) } msg, err := jsonparser.GetString(bodyDht, "message")
Found in cmd/utils.go by structure -
Function `getBootstrapPeers` has 6 return statements (exceeds 4 allowed).
// getBootstrapPeers fetches API to retrieve data from bootstrap peers func getBootstrapPeers(writer io.Writer, utilsService backend.Utility) ([]string, error) { var bootSlice []string bodyBoot, err := utilsService.ResponseBody(nil, "GET", "/api/v1/peers", "", nil) if err != nil { return nil, fmt.Errorf("unable to get response body: %w", err) } errMsg, err := jsonparser.GetString(bodyBoot, "error") if err == nil { return nil, fmt.Errorf(errMsg) } msg, err := jsonparser.GetString(bodyBoot, "message")
Found in cmd/utils.go by structure -
TODO found
// MemoryType represents the type of GPU memory, e.g., "GDDR6", "HBM2" // TODO: may be removed as it may be too specific for our case MemoryType string
Found in dms/resources/README.md by fixme -
TODO found
type Disk struct { // Model represents the disk model, e.g., "Samsung 970 EVO Plus", "Western Digital Blue SN550" // TODO: may be removed as Disk models will be usually irrelevant, right? Model string
Found in dms/resources/README.md by fixme -
TODO found
// Vendor represents the disk manufacturer, e.g., "Samsung", "Western Digital" // TODO: may be removed as Disk vendors will be usually irrelevant, right? Vendor string
Found in dms/resources/README.md by fixme -
TODO found
// Read speed in bytes per second // TODO: may be removed as it may be too specific for our case ReadSpeed uint64 // Write speed in bytes per second
Found in dms/resources/README.md by fixme -
TODO found
ReadSpeed uint64 // Write speed in bytes per second // TODO: may be removed as it may be too specific for our case WriteSpeed uint64 }
Found in dms/resources/README.md by fixme -
XXX found
// fetches the max clock speed of a single core // XXX: Assuming all cores have the same clock speed func hz_per_cpu() float64 { cores, _ := cpu.Info()
Found in dms/onboarding/available_resources.go by fixme -
TODO found
CpuNo: int(numCores), CpuHz: resources.Hz_per_cpu(), PriceCpu: 0, // TODO: Get price of CPU Ram: int(capacity.Memory), PriceRam: 0, // TODO: Get price of RAM
Found in dms/onboarding/handler.go by fixme -
TODO found
PriceCpu: 0, // TODO: Get price of CPU Ram: int(capacity.Memory), PriceRam: 0, // TODO: Get price of RAM Vcpu: int(math.Floor((float64(capacity.CPU)) / resources.Hz_per_cpu())), Disk: 0,
Found in dms/onboarding/handler.go by fixme -
TODO found
} // TODO: START NETWORKING AND OTHER WORKERS FOR THE NODE return nil, errors.New("NOT YET IMPLEMENTED")
Found in dms/onboarding/handler.go by fixme -
XXX found
db.ConnectDatabase() // XXX: wait for server to start properly before sending requests below // TODO: should be removed time.Sleep(time.Second * 5)
Found in dms/dms.go by fixme -
TODO found
// XXX: wait for server to start properly before sending requests below // TODO: should be removed time.Sleep(time.Second * 5)
Found in dms/dms.go by fixme -
TODO found
func Compare(l, r interface{}, preference ...Preference) models.Comparison { // TODO: it would be better to pass a pointer as this is a global structure var comparatorMap = initComparatorMap()
Found in dms/orchestrator/matching/comparator.go by fixme -
TODO found
result = models.Worse // TODO: this comparator does not take into account options when several job types are available and several job types are required // in the same data structure; this is why the test fails; }
Found in dms/orchestrator/matching/JobTypesComparator.go by fixme -
TODO found
var result models.Comparison result = models.Error // error is the default value // TODO: implement the comparison logic for the Capability type // after all the fields are implemented return result
Found in dms/orchestrator/matching/CapabilityComparator.go by fixme -
TODO found
// Deleted now because dependencies such as the docker package have been replaced with executor/docker func SanityCheck(gormDB *gorm.DB) { // TODO: sanity check of DMS last exit and correction of invalid states resources.CalcFreeResAndUpdateDB()
Found in dms/sanity_check.go by fixme -
XXX found
echo "Looking for old versions of nunet-dms ..." # XXX this can be removed once the new "nunet" binary has been in use for sometime if [ -f "/usr/bin/nunet-dms" ];then rm -f /usr/bin/nunet-dms
Found in maint-scripts/nunet-dms/DEBIAN/preinst by fixme -
TODO found
} // TODO(skylar): See if inline datum is present if input.DatumFile != "" { args = append(args, "--tx-in-inline-datum-present")
Found in utils/cardano/cardano.go by fixme -
TODO found
span.SetAttributes(attribute.String("URL", "/run/request-service")) // TODO: Uncomment after refactor. // kLogger.Info("Handle request service", span) // END
Found in api/run.go by fixme -
TODO found
// } c.AbortWithStatusJSON(500, gin.H{"error": "DeploymentRequestHandler not implemented"}) // TODO: Original func did not return a success response. Should we return it? }
Found in api/run.go by fixme -
TODO found
// @Router /run/checkpoints [get] func ListCheckpointHandler(c *gin.Context) { // TODO: Remove this section after refactor. checkpoints := checkpoint{} err := errors.New("non existant import path")
Found in api/run.go by fixme -
FIXME found
func getCustomCorsConfig() cors.Config { config := defaultConfig() // FIXME: This is a security concern. config.AllowOrigins = []string{"http://localhost:9991", "http://localhost:9992"} return config
Found in api/api.go by fixme -
TODO found
// @Router /device/status [get] func DeviceStatusHandler(c *gin.Context) { // TODO: handle this after refactor // status, err := libp2p.DeviceStatus() // if err != nil {
Found in api/device.go by fixme -
TODO found
} // TODO: handle this after refactor // err = libp2p.ChangeDeviceStatus(status.IsAvailable) // if err != nil {
Found in api/device.go by fixme -
TODO found
func (dhtValidator) Select(_ string, _ [][]byte) (int, error) { return 0, nil } // TODO remove the below when network package is fully implemented // UpdateKadDHT is a stub func (l *Libp2p) UpdateKadDHT() {
Found in network/libp2p/dht.go by fixme -
TODO found
// Libp2p contains the configuration for a Libp2p instance. // // TODO-suggestion: maybe we should call it something else like Libp2pPeer, // Libp2pHost or just Peer (callers would use libp2p.Peer...) type Libp2p struct {
Found in network/libp2p/libp2p.go by fixme -
TODO found
// New creates a libp2p instance. // // TODO-Suggestion: move models.Libp2pConfig to here for better readability. // Unless there is a reason to keep within models. func New(config *models.Libp2pConfig, fs afero.Fs) (*Libp2p, error) {
Found in network/libp2p/libp2p.go by fixme -
TODO found
err = l.advertiseForRendezvousDiscovery(context) if err != nil { // TODO: the error might be misleading as a peer can normally work well if an error // is returned here (e.g.: the error is yielded in tests even though all tests pass). zlog.Sugar().Errorf("failed to start network with randevouz discovery: %v", err)
Found in network/libp2p/libp2p.go by fixme -
TODO found
// Ping the remote address. The remote address is the encoded peer id which will be decoded and used here. // // TODO (Return error once): something that was confusing me when using this method is that the error is // returned twice if any. Once as a field of PingResult and one as a return value. func (l *Libp2p) Ping(ctx context.Context, peerIDAddress string, timeout time.Duration) (models.PingResult, error) {
Found in network/libp2p/libp2p.go by fixme -
TODO found
var advertisements []*commonproto.Advertisement for _, v := range addrInfo { // TODO: use go routines to get the values in parallel. bytesAdvertisement, err := l.DHT.GetValue(ctx, l.getCustomNamespace(key, v.ID.String())) if err != nil {
Found in network/libp2p/libp2p.go by fixme -
TODO found
*/ // TODO-pnet-1: we shouldn't handle configuration paths here, a general configuration path // should be provided by /internal/config.go func getBasePath(fs afero.Fs) (string, error) {
Found in network/libp2p/pnet.go by fixme -
TODO found
// If a swarm key is not found, generate a new one. // // TODO-ask: should we continue to generate a new swarm key if one is not found? // Or we should enforce the user to use some cmd/API rpc to generate a new one? func configureSwarmKey(fs afero.Fs) (pnet.PSK, error) {
Found in network/libp2p/pnet.go by fixme -
TODO found
} // TODO-ask: should we return psk fingerprint? return psk, nil }
Found in network/libp2p/pnet.go by fixme -
TODO found
swarmKeyWithCodec := fmt.Sprintf("/key/swarm/psk/1.0.0/\n/base64/\n%s\n", encodedKey) // TODO-pnet-1 nunetDir, err := getBasePath(fs) if err != nil {
Found in network/libp2p/pnet.go by fixme -
TODO found
) // TODO: pass the logger to the constructor and remove from here var ( zlog *otelzap.Logger
Found in network/libp2p/init.go by fixme -
TODO found
// NewNetwork returns a new network given the configuration. func NewNetwork(netConfig *models.NetworkConfig, fs afero.Fs) (Network, error) { // TODO: probable additional params to receive: DB, FileSystem if netConfig == nil { return nil, errors.New("network configuration is nil")
Found in network/network.go by fixme -
TODO found
return []s3Object{}, fmt.Errorf("failed to retrieve object metadata: %v", err) } // TODO-minor: validate checksum if provided if strings.HasPrefix(*headObjectOut.ContentType, "application/x-directory") {
Found in storage/s3/download.go by fixme -
TODO found
// NewDefaultVolumeController returns a new instance of BasicVolumeController // // TODO-BugFix [path]: volBasePath might not end with `/`, causing errors when calling methods. // We need to validate it using the `path` library or just verifying the string. func NewDefaultVolumeController(repo repositories.StorageVolumeRepository, volBasePath string, fs afero.Fs) (*BasicVolumeController, error) {
Found in storage/basic_controller/basic_controller.go by fixme -
TODO found
// where `name` is random. // // TODO-maybe [withName]: allow callers to specify custom name for path func (vc *BasicVolumeController) CreateVolume(volSource storage.VolumeSource, opts ...storage.CreateVolOpt) (models.StorageVolume, error) { vol := models.StorageVolume{
Found in storage/basic_controller/basic_controller.go by fixme -
TODO found
// It optionally can also set the CID and mark the volume as private. // // TODO-maybe [CID]: maybe calculate CID of every volume in case WithCID opt is not provided func (vc *BasicVolumeController) LockVolume(pathToVol string, opts ...storage.LockVolOpt) error { query := vc.repo.GetQuery()
Found in storage/basic_controller/basic_controller.go by fixme -
TODO found
// WithCID sets the CID of a given volume if already calculated // // TODO [validate]: check if CID provided is valid func WithCID(cid string) storage.LockVolOpt { return func(v *models.StorageVolume) {
Found in storage/basic_controller/basic_controller.go by fixme -
TODO found
// ListVolumes returns a list of all storage volumes stored on the database // // TODO [filter]: maybe add opts to filter results by certain values func (vc *BasicVolumeController) ListVolumes() ([]models.StorageVolume, error) { volumes, err := vc.repo.FindAll(context.Background(), vc.repo.GetQuery())
Found in storage/basic_controller/basic_controller.go by fixme -
TODO found
// GetSize returns the size of a volume // TODO-minor: identify which measurement type will be used func (vc *BasicVolumeController) GetSize(identifier string, idType storage.IDType) (int64, error) { query := vc.repo.GetQuery()
Found in storage/basic_controller/basic_controller.go by fixme -
TODO found
} // TODO-minor: compiler-time check for interface implementation var _ storage.VolumeController = (*BasicVolumeController)(nil)
Found in storage/basic_controller/basic_controller.go by fixme -
TODO found
// VolumeController is used to manage storage volumes. // // TODO-maybe: is the interface too big? We may have to split it? type VolumeController interface { // CreateVolume creates a directory where data can be stored, and returns a StorageVolume
Found in storage/volumes.go by fixme -
TODO found
// One of the opts may be a CID. Or the implementation might handle the CID calculation // // TODO-maybe: after volume is locked, callers should not be able to write data to it. LockVolume(pathToVol string, opts ...LockVolOpt) error
Found in storage/volumes.go by fixme -
TODO found
// GetSize returns the size of a volume // TODO-minor: identify which measurement type will be used GetSize(identifier string, idType IDType) (int64, error)
Found in storage/volumes.go by fixme -
TODO found
GetSize(identifier string, idType IDType) (int64, error) // TODO-maybe: encrypt/decrypt method might move to an unique EncryptVolume/DecryptVolume interfaces // or something else. // - Warning: if moved, EncryptionType field of StorageVolume must be updated somehow by the new interface
Found in storage/volumes.go by fixme -
TODO found
MessageHashAction string Action string // TODO: Add ContainerType field }
Found in models/machine.go by fixme -
TODO found
// created using the VolumeController, there will be no data in it by default. // // TODO-maybe [job]: should volumes be related to a job or []job? // // TODO-maybe: most of the fields should be private, callers shouldn't be able to altere
Found in models/storage.go by fixme -
TODO found
// TODO-maybe [job]: should volumes be related to a job or []job? // // TODO-maybe: most of the fields should be private, callers shouldn't be able to altere // the state of the volume except when using certain methods type StorageVolume struct {
Found in models/storage.go by fixme -
TODO found
// EncryptionType might be checked first if needed) // // TODO-maybe [type]: maybe it should be of type cid.CID CID string
Found in models/storage.go by fixme -
TODO found
// Size is the size of the storage volume // // TODO-maybe: if relying on a size field, we would have to be more careful // how state is being mutated (and they shouldn't be by the caller) // - Size might be calculated only when locking the volume also
Found in models/storage.go by fixme -
TODO found
// Warning: this is just a draft. And it might be moved to an Encryption package // // TODO: it must support encryption of files/directories, otherwise we have to // create another interface for the usecase type Encryptor interface {
Found in models/encryption.go by fixme -
TODO found
// Warning: this is just a draft. And it might be moved to an Encryption package // // TODO: it must support decryption of files/directories, otherwise we have to // create another interface for the usecase type Decryptor interface {
Found in models/encryption.go by fixme -
TODO found
) // TODO: Consider comments in this thread: https://gitlab.com/nunet/device-management-service/-/merge_requests/356#note_1997854443 // TODO: Consider comments in this thread: https://gitlab.com/nunet/device-management-service/-/merge_requests/356#note_1997875361
Found in models/comparison.go by fixme -
TODO found
// TODO: Consider comments in this thread: https://gitlab.com/nunet/device-management-service/-/merge_requests/356#note_1997854443 // TODO: Consider comments in this thread: https://gitlab.com/nunet/device-management-service/-/merge_requests/356#note_1997875361 // 'left' means 'this object' and 'right' means 'the supplied other object';
Found in models/comparison.go by fixme -
XXX found
) // XXX NewChatJoinCmd and NewChatStartCmd are similar, consider refactoring func NewChatJoinCmd(utilsService backend.Utility, wsClient backend.WebSocketClient) *cobra.Command { return &cobra.Command{
Found in cmd/chat_join.go by fixme -
TODO found
func (p *P2P) ClearIncomingChatRequests() error { log.Println("WARNING: Bypassing ClearIncomingChatRequests() in libp2p.go") // TODO: Uncomment after refactoring // return libp2p.ClearIncomingChatRequests() // END
Found in cmd/backend/libp2p.go by fixme -
TODO found
} // TODO: Handle this after refactor // getIncomingChatList unmarshal response body from API request into // libp2p.OpenStream slice and return list of chats
Found in cmd/utils.go by fixme -
XXX found
type Job struct { LogUpdateInterval int `mapstructure:"log_update_interval"` // in minutes TargetPeer string `mapstructure:"target_peer"` // specific peer to send deployment requests to - XXX probably not a good idea. Remove after testing stage. CleanupInterval int `mapstructure:"cleanup_interval"` // docker container and images clean up interval in days }
Found in internal/config/README.md by fixme -
XXX found
type Job struct { LogUpdateInterval int `mapstructure:"log_update_interval"` // in minutes TargetPeer string `mapstructure:"target_peer"` // specific peer to send deployment requests to - XXX probably not a good idea. Remove after testing stage. CleanupInterval int `mapstructure:"cleanup_interval"` // docker container and images clean up interval in days }
Found in internal/config/config.go by fixme